﻿using BLL.Base;
using BLL.custom;
using BLL.ERPAPI;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.DbEntity.sys;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Hosting;

namespace BLL.Plan
{
    public class PlanInfoBLL : SysFrameWork.PubMethod
    {
        Commands cmd;
        PubMethod method;
        SysFrameWork.LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        List<OperateModel> operList;
        OperateModel oper;
        PlanPaiChanBLL pcbll;

        public PlanInfoBLL()
        {
            cmd = new Commands();
            method = new PubMethod();
            userLogin = new SysFrameWork.LoginInfo();
            txt = new Tools.TxtLogHelper();
            pcbll = new PlanPaiChanBLL();
        }

        /// <summary>
        /// 读取生产计划临时存货数据
        /// </summary>
        /// <param name="keyCode">编码</param>
        /// <returns></returns>
        public ReturnResult loadTempProduct(string keyCode, string plType)
        {
            rsl = new ReturnResult();
            try
            {
                string key = userLogin.UserInfo().userCode + keyCode;
                var data = Tools.Cache.GetCache(key);
                if (data != null)
                {
                    var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(data.ToString());
                    //this.CreateBaoZhuang(list);
                    //this.getPlanNum("",ref list);
                    this.getPlanNum(plType, ref list);
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i]["doNum"].ToString() != "0")
                        {
                            if (list[i].ContainsKey("saleNum"))
                            {
                                list[i]["number"] = (Convert.ToDecimal(list[i]["saleNum"].ToString()) -
                              Convert.ToDecimal(list[i]["doNum"].ToString())).ToString();
                            }
                        }
                        list[i]["cu_gyName"] = "";//工序名称
                        list[i]["cu_gy"] = "";//工序
                    }
                    //rsl.Data = data;
                    rsl.Data = JsonConvert.SerializeObject(list);
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "数据读取失败";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 生产计划存货添加方法
        /// </summary>
        /// <param name="saleDatas">数据内容(可为空)</param>
        /// <returns></returns>
        public ReturnResult AddTempPlanProduct(string saleDatas, string keyCode, string num, string type = null)
        {
            rsl = new ReturnResult();
            try
            {
                List<Dictionary<string, string>> dList = new List<Dictionary<string, string>>();
                string key = userLogin.UserInfo().userCode + keyCode;
                if (!string.IsNullOrWhiteSpace(saleDatas))
                {//添加数据不为空，则将新数据覆盖旧数据
                    dList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(saleDatas);
                    if (type == "copy")
                    {
                        var cList = dList;//复制行 数据
                        var c_data = Tools.Cache.GetCache(key);
                        if (c_data != null)
                        {//现有列表
                            dList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(c_data.ToString());
                        }
                        #region 
                        //如果没填默认复制1行
                        if (string.IsNullOrWhiteSpace(num))
                        {
                            num = "1";
                        }
                        for (int i = 0; i < int.Parse(num); i++)
                        {
                            var d = new Dictionary<string, string>();
                            d["proCode"] = cList[0]["proCode"];
                            d["proName"] = cList[0]["proName"];
                            d["payDate"] = cList[0]["payDate"];
                            d["orderCode"] = cList[0]["orderCode"];
                            d["cu_yanse"] = cList[0]["cu_yanse"];
                            d["cu_shangbiao"] = cList[0]["cu_shangbiao"];
                            d["cu_diaopai"] = cList[0]["cu_diaopai"];
                            d["number"] = cList[0]["number"];
                            d["doNum"] = cList[0]["doNum"];
                            d["cuName"] = cList[0]["cuName"];
                            d["cuCode"] = cList[0]["cuCode"];
                            d["cu_neibaozhuangyq"] = cList[0]["cu_neibaozhuangyq"];
                            d["cu_zhuangxiangyq"] = cList[0]["cu_zhuangxiangyq"];
                            d["dataId"] = Guid.NewGuid().ToString();
                            d["cu_gy"] = cList[0]["cu_gy"];
                            d["cu_gyName"] = cList[0]["cu_gyName"];
                            d["memo"] = cList[0]["memo"];
                            d["gyCode"] = cList[0]["gyCode"];
                            d["gyName"] = cList[0]["gyName"];
                            d["zjMCode"] = cList[0]["zjMCode"];
                            d["zjMName"] = cList[0]["zjMName"];
                            d["zbMCode"] = cList[0]["zbMCode"];
                            d["zbMName"] = cList[0]["zbMName"];
                            dList.Add(d);
                        }

                        #endregion
                    }

                }
                else
                {
                    if (type == "yhd")
                    {
                        #region 新增要货单数据
                        var c_data = Tools.Cache.GetCache(key);
                        if (c_data != null)
                        {
                            dList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(c_data.ToString());
                            dList[0]["number"] = num;
                        }
                        #endregion
                    }
                    else
                    {
                        //数据为空 获取缓存数据，并新增一条空数据(备货计划)
                        #region 新增空数据
                        var c_data = Tools.Cache.GetCache(key);
                        if (c_data != null)
                        {
                            dList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(c_data.ToString());
                        }

                        StringBuilder sb = new StringBuilder();
                        var payDate = "";
                        sb.Append("select parValue from sys_parameters_info where parCode='bhdate' ");
                        sb.Append("and isDel=0 and enable='open' ");
                        var dateLong = cmd.GetDataTable(sb.ToString());
                        if (dateLong.Rows.Count > 0)
                        {
                            payDate = getNowDate(Convert.ToInt32(dateLong.Rows[0][0].ToString()));
                        }
                        else
                        {
                            payDate = getNowDate(1);
                        }

                        #region 
                        var d = new Dictionary<string, string>();
                        d["proCode"] = "";
                        d["proName"] = "";
                        d["payDate"] = payDate;
                        d["orderCode"] = "";
                        d["cu_yanse"] = "";
                        d["cu_shangbiao"] = "";
                        d["cu_diaopai"] = "";
                        d["number"] = "0";
                        d["doNum"] = "0";
                        d["cuName"] = "";
                        d["cuCode"] = "";
                        d["cu_neibaozhuangyq"] = "";
                        d["cu_zhuangxiangyq"] = "";
                        d["dataId"] = Guid.NewGuid().ToString();
                        d["cu_gy"] = "";
                        d["cu_gyName"] = "";
                        d["memo"] = "";
                        d["gyCode"] = "";
                        d["gyName"] = "";
                        d["zjMCode"] = "";
                        d["zjMName"] = "";
                        d["zbMCode"] = "";
                        d["zbMName"] = "";
                        dList.Add(d);
                        #endregion
                        #endregion
                    }

                }

                for (int i = 0; i < dList.Count; i++)
                {
                    if (!dList[i].ContainsKey("dataId"))
                    {
                        dList[i]["dataId"] = Guid.NewGuid().ToString();
                    }
                    if (!dList[i].ContainsKey("rowNO"))
                    {
                        dList[i]["rowNO"] = (i + 1).ToString();
                    }
                }
                Tools.Cache.SetCache(key, JsonConvert.SerializeObject(dList), DateTime.Now.AddMinutes(10));
                rsl.Data = JsonConvert.SerializeObject(dList);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 销售订单已下计划数
        /// </summary>
        /// <param name="list"></param>
        private void getPlanNum(string plType, ref List<Dictionary<string, string>> list)
        {
            try
            {
                StringBuilder sb;
                for (int i = 0; i < list.Count; i++)
                {
                    sb = new StringBuilder();
                    sb.Append("select isnull(SUM(CONVERT(decimal(18,0),p.number)),'0') num from pi_ProductionPlan_products p");
                    sb.Append(" inner join pi_ProductionPlan_info pi on p.plCode=pi.plCode");
                    sb.Append(" where p.isdel=0 and p.orderCode='" + list[i]["orderCode"].ToString() + "' and p.rowNO='" + list[i]["rowNO"].ToString() + "'");
                    if (!string.IsNullOrEmpty(list[i]["isosid"].ToString())) //aid->isosid
                    {
                        sb.Append(" and p.isosid='" + list[i]["isosid"].ToString() + "' ");
                    }
                    else
                    {
                        sb.Append(" and p.isosid is null ");
                    }
                    if (plType == "P-Pack")
                    {
                        sb.Append(" and pi.plType='P-Pack'");
                    }
                    else
                    {
                        sb.Append(" and pi.plType !='P-Pack'");
                    }
                    var table = cmd.GetDataTable(sb.ToString());
                    string num = "0";
                    if (table.Rows.Count > 0 && !string.IsNullOrEmpty(table.Rows[0]["num"].ToString()))
                    {
                        num = table.Rows[0]["num"].ToString();
                    }
                    list[i]["doNum"] = num;//已完成数
                }
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("获取已下计划数报错(getPlanNum):" + ex.Message);
            }
        }

        /// <summary>
        /// 添加包装方式
        /// </summary>
        private void CreateBaoZhuang(List<Dictionary<string, string>> list)
        {
            try
            {
                operList = new List<OperateModel>();
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_GxPrice_info where isdel=0");
                var cgxTable = cmd.GetDataTable(sb.ToString());
                List<string> reList = new List<string>();
                DbGongXuPrice gxP;
                int i = 0;
                foreach (var d in list)
                {
                    i++;
                    //cu_baozhuang
                    if (!d.ContainsKey("cu_neibaozhuangyq") || string.IsNullOrWhiteSpace(d["cu_neibaozhuangyq"]))
                    {
                        continue;
                    }
                    string proCode = d["proCode"];
                    string bzfs = d["cu_neibaozhuangyq"];
                    if (!string.IsNullOrWhiteSpace(bzfs))
                    {
                        if (!reList.Contains(bzfs))
                        {
                            sb.Clear();
                            sb.Append("select * from fun_CommonData_Info where cMemo like '%'+ (");
                            sb.Append("select typeCode from fun_Inventory_Info where proCode='" + proCode + "'");
                            sb.Append(" and baseCode='" + userLogin.UserInfo().baseCode + "')+'%'  and cType='SCTYPE'");
                            var table = cmd.GetDataTable(sb.ToString());
                            if (table.Rows.Count > 0)
                            {
                                var dr = cgxTable.Select("cgxName='" + bzfs.Trim() + "' and proType='" + table.Rows[0]["cCode"] + "'");
                                if (dr.Length > 0)
                                {
                                    continue;
                                }

                                gxP = new DbGongXuPrice();
                                gxP.cgxCode = getTimeString() + i.ToString();
                                gxP.cgxName = bzfs.Trim();
                                gxP.createtime = getNow();
                                gxP.createuser = userLogin.UserInfo().userCode;
                                gxP.gxCode = "GxBZ";
                                gxP.isDel = 0;
                                gxP.nPrice = "0";
                                gxP.yPrice = "0";
                                gxP.proType = table.Rows[0]["cCode"].ToString();
                                oper = new OperateModel();
                                oper.Data = gxP;
                                oper.Types = OperateModel.OperateType.Add;
                                operList.Add(oper);
                            }
                            reList.Add(bzfs);
                        }

                    }
                }
                if (operList.Count > 0)
                {
                    cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("包装方式创建报错(CreateBaoZhuang):" + ex.Message);
            }

        }

        /// <summary>
        /// 添加生产计划
        /// </summary>
        /// <param name="mData"></param>
        /// <param name="cData"></param>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult AddProductPlan(string mData, string cData, string plCode)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                operList = new List<OperateModel>();
                List<string> orList = new List<string>();
                List<string> cuList = new List<string>();
                bool isAdd = false;
                if (string.IsNullOrWhiteSpace(cData))
                {
                    rsl.Message = "计划没有关联任何生产存货";
                    return rsl;
                }
                var cList = JsonConvert.DeserializeObject<List<JObject>>(cData);
                var mList = JsonConvert.DeserializeObject<JObject>(mData);
                foreach (JObject obj in cList)
                {
                    #region  保存织造计划时，必须选择工艺 和机台   已注释
                    //if (mList["plType"].ToString() == "P-ZhiZao")
                    //{
                    //    if (string.IsNullOrWhiteSpace(obj["gyCode"].ToString()))
                    //    {
                    //        rsl.Message = "请选择生产工艺";
                    //        return rsl;
                    //    }
                    //    if (string.IsNullOrWhiteSpace(obj["zjMCode"].ToString()) || string.IsNullOrWhiteSpace(obj["zbMCode"].ToString()))
                    //    {
                    //        rsl.Message = "请选择机台";
                    //        return rsl;
                    //    }
                    //}
                    #endregion

                    if (string.IsNullOrWhiteSpace(plCode))
                    {
                        //if (obj["saleNum"] != null && mList["plType"].ToString()== "P-Sale")
                        //{
                        //    if (Convert.ToDecimal(obj["doNum"].ToString()) + Convert.ToDecimal(obj["number"].ToString())
                        //    > Convert.ToDecimal(obj["saleNum"].ToString()))
                        //    {
                        //        rsl.Message = "该销售订单总计划生产数量>订单数量，请检查计划数量";
                        //        return rsl;
                        //    }
                        //}
                    }
                    else
                    {
                        //织造计划修改时，只要没报工就可以修改
                        sb.Clear();
                        if(mList["plType"].ToString()== "P-ZhiZao")
                        {
                            sb.Append("select * from pi_PlanBaogong_main where ppId='" + obj["id"].ToString() + "' and isDel=0");
                        }
                        else
                        {
                            sb.Append("select * from pi_PlanPaiGong_info where ppId='" + obj["id"].ToString() + "' and isDel=0");
                        }
                        var bgTable = cmd.GetDataTable(sb.ToString());
                        if (bgTable.Rows.Count > 0)
                        {
                            var msg = "此计划已派工，暂不支持修改";
                            if (mList["plType"].ToString() == "P-ZhiZao")
                            {
                                msg= "此计划已报工，暂不支持修改";
                            }
                            rsl.Message = msg;
                            return rsl;
                        }

                        if (string.IsNullOrWhiteSpace(obj["number"].ToString()) ||
                            Convert.ToDecimal(obj["number"].ToString()) == 0)
                        {
                            rsl.Message = "计划生产数量不允许为空/0，请检查计划数量";
                            return rsl;
                        }
                    }

                    if (!orList.Contains(obj["orderCode"].ToString()))
                    {
                        orList.Add(obj["orderCode"].ToString());
                    }
                    if (!cuList.Contains(obj["cuName"].ToString()))
                    {
                        cuList.Add(obj["cuName"].ToString());
                    }

                }

                if (string.IsNullOrWhiteSpace(plCode))
                {
                    #region 计划编码不存在，生成新的计划编码
                    string codeLength = Tools.ConfigReader.Reader["CodeLength"];
                    string pCode = "";
                    if (mList["plType"].ToString() == "P-Pack")
                    {
                        pCode = "PK";
                    }
                    else if (mList["plType"].ToString() == "P-Sale")
                    {
                        pCode = "SO";
                    }
                    else if (mList["plType"].ToString() == "P-BeiHuo")
                    {
                        pCode = "PO";
                    }
                    else if (mList["plType"].ToString() == "P-ZhiZao")
                    {
                        pCode = "ZZ";
                    }
                    else
                    {
                        pCode = "NP";
                    }
                    isAdd = true;

                    plCode = CreatePlanCodeInfo(pCode, "生产计划编码", int.Parse(codeLength));
                    #endregion
                }

                #region 计划关联存货
                DbProductionPlanPro pp;
                int rowNo = 0;
                double pNum = 0;

                foreach (JObject obj in cList)
                {
                    #region 如果是根据要货单创建计划 保存时判断要货单是否存在（考虑销售删了但计划员这没刷新） 目前无要货单， 已注释
                    //if (obj["aid"] != null && !string.IsNullOrWhiteSpace(obj["aid"].ToString()))
                    //{
                    //    sb.Clear();
                    //    sb.Append("select * from pi_proAsk_info  where isdel =0  and id = " + obj["aid"].ToString());
                    //    var aTable = cmd.GetDataTable(sb.ToString());
                    //    if (aTable.Rows.Count < 1)
                    //    {
                    //        rsl.Message = "要货单不存在，已被相关人员删除，请刷新列表。";
                    //        return rsl;
                    //    }
                    //}
                    #endregion

                    rowNo++;

                    if (string.IsNullOrWhiteSpace(obj["proCode"].ToString()))
                    {
                        continue;
                    }

                    #region 子表

                    if (obj["number"] != null && !string.IsNullOrWhiteSpace(obj["number"].ToString()) && obj["number"].ToString() != "0")
                    {
                        pNum += double.Parse(obj["number"].ToString());
                        #region 存货信息添加
                        oper = new OperateModel();
                        pp = new DbProductionPlanPro();
                        pp = JsonConvert.DeserializeObject<DbProductionPlanPro>(JsonConvert.SerializeObject(obj));
                        if (string.IsNullOrWhiteSpace(obj["orderCode"].ToString()))
                        {
                            if (IsNum(obj["dataId"].ToString()))
                            {
                                pp.rowNO = obj["rowNO"].ToString();
                            }
                            else
                            {
                                pp.rowNO = rowNo.ToString();
                            }

                            #region 空值验证
                            if (obj["aid"] == null || string.IsNullOrWhiteSpace(obj["aid"].ToString()))  //要货单创建的计划不用验证
                            {
                                if (obj["payDate"] == null || string.IsNullOrWhiteSpace(obj["payDate"].ToString()))
                                {
                                    rsl.Message = "请输入交付日期";
                                    return rsl;
                                }
                                if(mList["plType"].ToString() != "P-ZhiZao")
                                {
                                    //织造计划不需要颜色商标等信息
                                    if (obj["cu_yanse"] == null || string.IsNullOrWhiteSpace(obj["cu_yanse"].ToString()))
                                    {
                                        rsl.Message = "请选择颜色";
                                        return rsl;
                                    }
                                    if (obj["cu_shangbiao"] == null || string.IsNullOrWhiteSpace(obj["cu_shangbiao"].ToString()))
                                    {
                                        rsl.Message = "请选择商标";
                                        return rsl;
                                    }
                                    if (obj["cu_neibaozhuangyq"] == null || string.IsNullOrWhiteSpace(obj["cu_neibaozhuangyq"].ToString()))
                                    {
                                        rsl.Message = "请输入内包装要求";
                                        return rsl;
                                    }
                                    if (obj["cu_zhuangxiangyq"] == null || string.IsNullOrWhiteSpace(obj["cu_zhuangxiangyq"].ToString()))
                                    {
                                        rsl.Message = "请输入装箱要求";
                                        return rsl;
                                    }
                                }
                                
                            }
                            #endregion
                        }
                        pp.isdel = 0;
                        pp.plCode = plCode;
                        //var a = obj["cu_gy"];
                        if (string.IsNullOrEmpty(obj["cu_gy"].ToString()))
                        {
                            pp.status = "ps-gy-set";//默认工艺配置
                        }
                        else
                        {
                            pp.status = "ps-pg-set";//默认待派工
                        }
                        //pp.prlCode = plCode + "-" + rowNo ;
                        oper.Data = pp;
                        pp.createtime = getNow();
                        pp.createuser = userLogin.UserInfo().userCode;
                        if (pp.id != null)
                        {
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "id";
                            pp.prlCode = obj["prlCode"].ToString();
                        }
                        else
                        {
                            pp.prlCode = plCode + "-" + rowNo;
                            oper.Types = OperateModel.OperateType.Add;
                        }
                        operList.Add(oper);
                        #endregion
                    }
                    else
                    {
                        rsl.Message = "请输入数量";
                        return rsl;
                    }

                    //rowNo++;
                    #endregion

                }
                #endregion

                #region  先添加存货信息，如果operList没有东西，就是没加上有效存货信息，这返回一下错误，不然会保存空的计划
                if (operList.Count < 1)
                {
                    rsl.Message = "未正确添加存货信息，请检查是否添加了存货";
                    return rsl;
                }
                #endregion

                #region 主生产计划
                var plan = JsonConvert.DeserializeObject<DbProductionPlan>(mData);
                plan.number = pNum.ToString();
                if(mList["plType"].ToString() == "P-Pack" && mList["isNeedPack"]!=null && mList["isNeedPack"].ToString() == "on")
                {
                    plan.needPack = 1;
                }
                else
                {
                    plan.needPack = 0;
                }
                oper = new OperateModel();

                if (orList.Count > 0)
                {
                    plan.relationOrder = string.Join(",", orList);
                }
                plan.plCode = plCode;
                plan.createtime = getNow();
                if (cuList.Count > 0)
                {
                    plan.customers = string.Join(",", cuList);
                }
                plan.createuser = userLogin.UserInfo().userCode;
                if (plan.plType == "P-BeiHuo")
                {
                    //plan.pStatus = "approving";
                    plan.pStatus = "pass";
                }
                else
                {
                    plan.pStatus = "pass";
                }
                if (string.IsNullOrWhiteSpace(plan.pLevel))
                {
                    plan.pLevel = "100";
                }
                plan.status = "ps-pg-set";//状态默认为待派工
                if (isAdd)
                {
                    oper.Types = OperateModel.OperateType.Add;
                }
                else
                {
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "plCode";
                }
                oper.Data = plan;
                operList.Add(oper);
                #endregion

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        #region 保存计划完成后，织造计划同时保存工艺并生成派工单  已注释
                        //if(mList["plType"].ToString() == "P-ZhiZao")
                        //{
                        //    if (isAdd)
                        //    {
                        //        #region 新增时
                        //        sb.Clear();
                        //        sb.Append("select * from pi_ProductionPlan_products where isdel=0 and plCode='" + plCode + "'");
                        //        var plTable = cmd.GetDataTable(sb.ToString());

                        //        rowNo = 0;
                        //        foreach (JObject obj in cList)
                        //        {
                        //            rowNo++;
                        //            var row = plTable.Select("rowNO='" + rowNo + "'");    //获取ppid
                        //            if (row.Length > 0)
                        //            {
                        //                //保存计划工艺
                        //                var processRsl = pcbll.SetPlanGongYi(row[0]["id"].ToString(), obj["gyCode"].ToString());
                        //                if (!processRsl.Result)
                        //                {
                        //                    return processRsl;
                        //                }

                        //                //派工
                        //                var list = new List<Object>();

                        //                //var pgRsl = pcbll.AddZZPaiGongTask();
                        //            }
                        //            else
                        //            {
                        //                rsl.Message = "找不到相关计划："+ plCode+","+rowNo;
                        //                return rsl;
                        //            }
                                    
                        //        }
                               
                        //        #endregion
                        //    }
                        //    else
                        //    {
                        //        #region 修改时

                        //        #endregion
                        //    }

                        //}
                        #endregion
                        Tools.Cache.RemoveAllCache();
                    }
                }
                else
                {
                    rsl.Message = "没有要提交的数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        public ReturnResult saveProAsk(string cData)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                operList = new List<OperateModel>();
                if (string.IsNullOrWhiteSpace(cData))
                {
                    rsl.Message = "要货单没有任何生产存货";
                    return rsl;
                }
                var cList = JsonConvert.DeserializeObject<List<JObject>>(cData);

                #region 判断录入的颜色商标是否是该存货的自由项
                sb.Append("select cName , parentCode,cType from fun_CommonData_Info where specFile='" + userLogin.UserInfo().baseCode + "' ");
                sb.Append(" and isDel=0 and status='Y' and  cType in ('proColor','proBrand')");// and parentCode='"+cList[0]["proCode"].ToString()+"'
                var cTable = cmd.GetDataTable(sb.ToString());   //获取全部颜色和商标

                var allys = new List<string>(); var allsb = new List<string>(); //全部的颜色/商标

                string codeLength = Tools.ConfigReader.Reader["CodeLength"];

                //var aCode = CreatePlanCodeInfo("ask", "要货单编码", int.Parse(codeLength));

                DbProAsk ask;

                var isallc = false; var isalls = false;//是否获取全部的自由项   标识

                foreach (JObject obj in cList)
                {
                    
                    if (string.IsNullOrWhiteSpace(obj["proCode"].ToString()))
                    {
                        continue;
                    }

                    if (string.IsNullOrWhiteSpace(obj["cuCode"].ToString()))
                    {
                        rsl.Message = "请选择客户";
                        return rsl;
                    }

                    #region 存货自由项验证
                    var cr = cTable.Select(" parentCode='" + obj["proCode"].ToString() + "' and  cType='proColor' ");//获取录入的存货对应全部的颜色
                    var sr = cTable.Select(" parentCode='" + obj["proCode"].ToString() + "' and  cType='proBrand' ");//获取录入的存货对应全部的商标
                    #region

                    #region 
                    if (cr.Length < 1)
                    {
                        isallc = true;
                        //if (string.IsNullOrWhiteSpace(allys)) 
                        if (allys.Count<1) 
                        { 
                            cr = cTable.Select(" cType='proColor' and parentCode is null");//如果没有获取到，就取全部的颜色(allys,因为数量太大，只获取一次（为空时）)
                        }
                    }
                    else 
                    {
                        isallc = false;
                    }

                    if (sr.Length < 1 )
                    {
                        isalls = true;
                        //if (string.IsNullOrWhiteSpace(allsb)) 
                        if (allsb.Count<1) 
                        { 
                            sr = cTable.Select(" cType='proBrand' and parentCode is null ");//如果没有获取到，就取全部的商标(allsb,因为数量太大，只获取一次（为空时）)
                        }
                    }
                    else 
                    {
                        isalls = false;
                    }

                    #endregion

                    var colors = new List<string>(); var shangbiaos = new List<string>();

                    #region 分情况获取颜色
                    //如果需要获取全部颜色，并且allys是空时，查全部 赋值给colors和allys
                    if (isallc && allys.Count < 1)
                    {
                        foreach (var dr in cr)
                        {
                            colors.Add(dr["cName"].ToString() );
                        }
                        allys = colors;
                    }
                    //如果不需要获取全部的颜色，直接查存货对应的颜色，赋值给colors
                    else if (!isallc)
                    {
                        foreach (var dr in cr)
                        {
                            colors.Add(dr["cName"].ToString());
                        }
                    }
                    //需要获取全部颜色，但allys有值，不再遍历，直接取allys的值
                    else
                    {
                        colors = allys;
                    }
                    #endregion
                    #region 分情况获取商标  同上
                    if (isalls && allsb.Count < 1)
                    {
                        foreach (var dr in sr)
                        {
                            shangbiaos.Add(dr["cName"].ToString() );
                        }
                        allsb = shangbiaos;
                    }
                    else if (!isalls)
                    {
                        foreach (var dr in sr)
                        {
                            shangbiaos.Add(dr["cName"].ToString());
                        }
                    }
                    else
                    {
                        shangbiaos = allsb;
                    }
                    #endregion

                    if (!colors.Contains(obj["cu_yanse"].ToString()))
                    {
                        rsl.Message = "存货:" + obj["proCode"].ToString() + "不包含此颜色:'" + obj["cu_yanse"].ToString() + "'";
                        return rsl;
                    }
                    if (!shangbiaos.Contains(obj["cu_shangbiao"].ToString()))
                    {
                        rsl.Message = "存货:" + obj["proCode"].ToString() + "不包含此商标:'" + obj["cu_shangbiao"].ToString() + "'";
                        return rsl;
                    }
                    #endregion

                    #endregion

                    if (obj["number"] != null && !string.IsNullOrWhiteSpace(obj["number"].ToString()) && obj["number"].ToString() != "0")
                    {
                        var aCode = CreatePlanCodeInfo("ask", "要货单编码", int.Parse(codeLength));

                        #region 信息添加
                        oper = new OperateModel();
                        ask = new DbProAsk();
                        ask = JsonConvert.DeserializeObject<DbProAsk>(JsonConvert.SerializeObject(obj));
                        ask.isdel = 0;
                        ask.isFinish = 0;
                        ask.aCode = aCode;
                        ask.status = 0;
                        ask.createtime = getNow();
                        ask.createuser = userLogin.UserInfo().userCode;
                        oper.Data = ask;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        #endregion
                    }
                    else
                    {
                        rsl.Message = "请输入数量";
                        return rsl;
                    }

                    //rowNo++;
                    

                    #endregion 

                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        Tools.Cache.RemoveAllCache();
                    }
                }
                else
                {
                    rsl.Message = "没有要提交的数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }



        /// <summary>
        /// 计划工艺数据保存
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SavePlanGongYi(string datas)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                DbPlanGongXu pgx;
                if (string.IsNullOrWhiteSpace(datas))
                {
                    rsl.Message = "没有任何数据要保存";
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from pi_ProductionPlan_process where proCode='" + json["proCode"] + "'");
                sb.Append(" and orderCode='" + json["orderCode"] + "' and rowNo='" + json["rowNo"] + "'");
                if (!string.IsNullOrWhiteSpace(json["plCode"].ToString()))
                {
                    sb.Append(" and plCode='" + json["plCode"].ToString() + "'");
                }
                var pgyTable = cmd.GetDataTable(sb.ToString());
                sb.Clear();
                sb.Append("select * from fun_GxPrice_info where isdel=0 and proType in(");
                sb.Append("select cCode from fun_CommonData_Info where cMemo like '%'+ (");
                sb.Append("select typeCode from fun_Inventory_Info where proCode='" + json["proCode"] + "')+'%')");
                var gxTable = cmd.GetDataTable(sb.ToString());
                var cArr = json["gyData"].ToString().Split(',');
                #region 添加
                for (int i = 0; i < cArr.Length; i++)
                {
                    if (!string.IsNullOrWhiteSpace(cArr[i]))
                    {
                        var dr = pgyTable.Select("gxCode='" + cArr[i].Trim() + "'");
                        if (dr.Length < 1)
                        {
                            #region 构建数据模型
                            pgx = new DbPlanGongXu();
                            oper = new OperateModel();
                            dr = gxTable.Select("cgxCode='" + cArr[i].Trim() + "'");
                            if (dr.Length > 0)
                            {
                                pgx.isChild = 1;
                            }
                            else
                            {
                                pgx.isChild = 0;
                                continue;
                            }
                            pgx.plCode = json["plCode"].ToString();
                            pgx.orderCode = json["orderCode"].ToString();
                            pgx.rowNo = json["rowNo"].ToString();
                            pgx.gxCode = cArr[i];
                            pgx.parentCode = dr[0]["gxCode"].ToString();
                            pgx.proCode = json["proCode"].ToString();
                            pgx.createtime = getNow();
                            pgx.createuser = userLogin.UserInfo().userCode;
                            pgx.status = "ps-dsc";
                            oper.Types = OperateModel.OperateType.Add;
                            oper.Data = pgx;
                            operList.Add(oper);
                            #endregion
                        }
                    }
                }
                #endregion
                #region 删除
                foreach (DataRow r in pgyTable.Rows)
                {
                    string gxCode = r["gxCode"].ToString();
                    bool isDel = true;
                    if (r["isChild"].ToString().Equals("1"))
                    {
                        foreach (string gStr in cArr)
                        {
                            if (gStr == gxCode)
                            {
                                isDel = false;
                                break;
                            }
                        }
                    }
                    if (isDel)
                    {
                        pgx = new DbPlanGongXu();
                        pgx.id = int.Parse(r["id"].ToString());
                        oper = new OperateModel();
                        oper.Data = pgx;
                        oper.Types = OperateModel.OperateType.Delete;
                        operList.Add(oper);
                    }
                }
                #endregion

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "工序没有发生变化";
                    rsl.Result = true;
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 计划工艺临时保存
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SaveTempPlanGongYi(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                string key = string.Format("{0}{1}{2}-PGY", json["orderCode"], json["rowNo"], userLogin.UserInfo().userCode);
                if (string.IsNullOrWhiteSpace(datas))
                {
                    var data = Tools.Cache.GetCache(key);
                    if (data != null)
                    {
                        rsl.Data = data;
                        rsl.Result = true;
                    }
                    else
                    {
                        rsl.Message = "数据读取失败";
                    }
                    return rsl;
                }
                else
                {
                    Tools.Cache.SetCache(key, datas);
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 要货单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getProAskList(string pageIndex, string pageSize, ref string pageCount, string condition, string sign = null)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }

                StringBuilder sb = new StringBuilder();
                var json = new JObject();
                #region 检索条件
                sb.Clear();
                sb.Append(" isdel=0 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name.ToString().Equals("isSale"))
                            {
                                if (obj.Value.ToString().Equals("1"))
                                {
                                    if (userLogin.UserInfo().isAdmin == 1)
                                    {
                                        sb.Append("isFinish=0 ");
                                    }
                                    else
                                    {
                                        sb.Append("createuser='" + userLogin.UserInfo().userCode + "' ");
                                    }
                                }
                                else
                                {
                                    sb.Append("isFinish=0 ");
                                }

                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                #endregion

                var list = cmd.PageList("V_proAsk_info", pageIndex, pageSize, sb.ToString(), "createtime desc", ref pageCount);

                #region 数据处理
                var table = new DataTable();
                foreach (var s in list)
                {
                    s["isSale"] = json["isSale"].ToString();//isSale标识，用于 给销售看的要货单 页面 显示删除按钮

                    // hasPlan 判断要货单是否创建计划
                    sb.Clear();
                    sb.Append(" select * from V_ProductionPlan_products where isdel = 0 and aid = " + s["aid"]);
                    table = cmd.GetDataTable(sb.ToString());
                    if (table.Rows.Count > 0)
                    {
                        s["hasPlan"] = "1";//已创建计划
                        #region 创建销售计划数
                        var rows = table.Select("plType='P-Sale'");
                        var num = 0;
                        if (rows.Length > 0)
                        {
                            foreach (DataRow dr in rows)
                            {
                                num = num + int.Parse(dr["number"].ToString());
                            }

                        }
                        s["sNum"] = num.ToString();
                        #endregion
                        #region 创建包装计划数
                        rows = table.Select("plType='P-Pack'");
                        num = 0;
                        if (rows.Length > 0)
                        {
                            foreach (DataRow dr in rows)
                            {
                                num = num + int.Parse(dr["number"].ToString());
                            }
                        }
                        s["pNum"] = num.ToString();
                        #endregion
                    }
                    else
                    {
                        s["hasPlan"] = "0";
                    }



                }
                #endregion
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 生产（改标）计划列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getPlanList(string pageIndex, string pageSize, ref string pageCount, string condition, string sign = null)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }

                StringBuilder sb = new StringBuilder();
                var maxR = pcbll.getMaxRole();

                #region 检索条件
                sb.Append(" isdel=0 ");
                if (string.IsNullOrWhiteSpace(sign))  //生产计划
                {  
                    sb.Append(" and plType not in ('P-Pack','P-ZhiZao') ");
                }
                else
                {
                    if (sign == "bl")
                    {
                        sb.Append(" and plType !='P-ZhiZao' ");
                    }
                }
                if (userLogin.UserInfo().isAdmin == 0 && !userLogin.UserInfo().powerRole.Equals(maxR))
                {
                    sb.Append(" and  createuser='" + userLogin.UserInfo().userCode + "' ");
                }
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (obj.Name == "status" || obj.Name == "switch")
                            {
                                continue;
                            }
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "cStatus")
                            {
                                var sArr = obj.Value.ToString().Split(',');
                                string status = "";
                                foreach (string s in sArr)
                                {
                                    if (!string.IsNullOrWhiteSpace(s))
                                    {
                                        status += "'" + s + "',";
                                    }
                                }
                                sb.Append("status in (" + status.TrimEnd(',') + ")");
                            }
                            else if (obj.Name == "sDate")
                            {
                                sb.Append(" convert(datetime,createtime, 20)" + " >='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {//结束时间
                                sb.Append(" convert(date,createtime, 20)" + "<= '" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "proName")
                            {
                                #region  通过存货名称查到相关计划，然后再进行计划筛选
                                StringBuilder prosb = new StringBuilder();
                                prosb.Append("select DISTINCT plCode from V_ProductionPlan_products where proName ");
                                prosb.Append("like  '%" + obj.Value.ToString() + "%'");
                                var pTable = cmd.GetDataTable(prosb.ToString());
                                if (pTable.Rows.Count > 0)
                                {
                                    var plCodes = "";
                                    foreach (DataRow dr in pTable.Rows)
                                    {
                                        plCodes += "'" + dr[0].ToString() + "',";
                                    }
                                    sb.Append(" plCode in (" + plCodes.TrimEnd(',') + ") ");
                                }
                                #endregion 
                            } 
                            else if (obj.Name == "isPrint")
                            {
                                if (obj.Value.ToString().Equals("0"))
                                {
                                    sb.Append(" isPrint is null ");
                                }
                                else
                                {
                                    sb.Append(" isPrint ='" + obj.Value.ToString() + "' ");
                                }
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                #endregion

                var list = cmd.PageList("V_ProductionPlan_products", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                getPlanRelationData(ref list);
                getGYName(ref list);
                if (!string.IsNullOrWhiteSpace(sign))
                    getPlannNum(ref list);//获取计划的不合格数
                #region  只看有次品筛选
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var jsons = JsonConvert.DeserializeObject<JObject>(condition);
                    if (jsons["switch"] != null && jsons["switch"].ToString() == "on")
                    {
                        var newList = list.Where(p => p["nNum"] != "0.00").ToList();
                        list = newList;
                    }
                }
                #endregion

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 织造计划列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult ToZhiZaoTask(string pageIndex, string pageSize, ref string pageCount, string condition, string sign = null)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }

                StringBuilder sb = new StringBuilder();
                var maxR = pcbll.getMaxRole();

                #region 检索条件
                sb.Append(" isdel=0 ");
                if (string.IsNullOrWhiteSpace(sign))
                    sb.Append(" and plType='P-ZhiZao' ");
                if (userLogin.UserInfo().isAdmin == 0 && !userLogin.UserInfo().powerRole.Equals(maxR))
                {
                    sb.Append(" and  createuser='" + userLogin.UserInfo().userCode + "' ");
                }
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (obj.Name == "status" || obj.Name == "switch")
                            {
                                continue;
                            }
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "cStatus")
                            {
                                var sArr = obj.Value.ToString().Split(',');
                                string status = "";
                                foreach (string s in sArr)
                                {
                                    if (!string.IsNullOrWhiteSpace(s))
                                    {
                                        status += "'" + s + "',";
                                    }
                                }
                                sb.Append("status in (" + status.TrimEnd(',') + ")");
                            }
                            else if (obj.Name == "sDate")
                            {
                                sb.Append(" convert(datetime,createtime, 20)" + " >='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {//结束时间
                                sb.Append(" convert(date,createtime, 20)" + "<= '" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "proName")
                            {
                                #region  通过存货名称查到相关计划，然后再进行计划筛选
                                StringBuilder prosb = new StringBuilder();
                                prosb.Append("select DISTINCT plCode from V_ProductionPlan_products where proName ");
                                prosb.Append("like  '%" + obj.Value.ToString() + "%'");
                                var pTable = cmd.GetDataTable(prosb.ToString());
                                if (pTable.Rows.Count > 0)
                                {
                                    var plCodes = "";
                                    foreach (DataRow dr in pTable.Rows)
                                    {
                                        plCodes += "'" + dr[0].ToString() + "',";
                                    }
                                    sb.Append(" plCode in (" + plCodes.TrimEnd(',') + ") ");
                                }
                                #endregion 
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                #endregion

                var list = cmd.PageList("V_ProductionPlan_products", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                getPlanRelationData(ref list);
                getGYName(ref list);
                if (!string.IsNullOrWhiteSpace(sign))
                    getPlannNum(ref list);//获取计划的不合格数

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        /// <summary>
        /// 任务中心列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getTaskCenter(string pageIndex, string pageSize, ref string pageCount, string condition, string sign = null)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }

                StringBuilder sb = new StringBuilder();

                #region 检索条件
                sb.Clear();
                sb.Append(" businessType='changeTag' ");

                var json = new JObject();
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (obj.Name == "status" || obj.Name == "switch")
                            {
                                continue;
                            }
                            if (obj.Name.ToString().Equals("isSale"))
                            {
                                if (obj.Value.ToString().Equals("1"))
                                {
                                    if (userLogin.UserInfo().isAdmin != 1)
                                    {
                                        sb.Append(" and createuser='" + userLogin.UserInfo().userCode + "' ");
                                    }
                                }

                            }
                        }
                    }
                }
                #endregion

                var list = cmd.PageList("V_TaskCenter", pageIndex, pageSize, sb.ToString(), "createtime desc", ref pageCount);

                #region 数据处理
                var table = new DataTable();
                foreach (var s in list)
                {
                    //手动创建的允许删除，自动任务创建的暂不支持删除
                    if (!string.IsNullOrEmpty(s["createuser"].ToString()))
                    {
                        s["canDel"] = "1";
                    }
                    else
                    {
                        s["canDel"] = "0";
                    }
                    s["isSale"] = json["isSale"].ToString();//isSale标识，用于 给销售看的要货单 页面 显示删除按钮
                }
                #endregion

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult LoadTargetProducts(string pageIndex, string pageSize, ref string pageCount, string condition, string taskCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }

                var list = new List<Restock_Keyword>();

                //var taskCenter_Sql_template = "select * from sys_TaskCenter_info where taskcode = '{0}'";
                var taskCenter_Sql_template = "select t.*,u.userName from sys_TaskCenter_info t " +
                    "left join sys_users_info u on u.userCode = t.relationPeople and u.isdel = 0 and status = 'Y' where taskcode = '{0}'";
                var taskCenter_Sql = string.Format(taskCenter_Sql_template, taskCode);

                var taskCenter_Dt = cmd.GetDataTable(taskCenter_Sql);
                var contents = taskCenter_Dt.Rows[0]["contents"].ToString();

                list = JsonConvert.DeserializeObject<List<Restock_Keyword>>(contents);
                list[0].relationPeople= taskCenter_Dt.Rows[0]["relationPeople"].ToString();
                list[0].userName = taskCenter_Dt.Rows[0]["userName"].ToString();

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 计划列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getAllPlanList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }

                StringBuilder sb = new StringBuilder();
                var maxR = pcbll.getMaxRole();

                #region 检索条件
                sb.Append(" isdel=0 ");
                if (userLogin.UserInfo().isAdmin == 0 && !userLogin.UserInfo().powerRole.Equals(maxR))
                {
                    sb.Append(" and  createuser='" + userLogin.UserInfo().userCode + "' ");
                }
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (obj.Name == "status")
                            {
                                continue;
                            }
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "cStatus")
                            {
                                var sArr = obj.Value.ToString().Split(',');
                                string status = "";
                                foreach (string s in sArr)
                                {
                                    if (!string.IsNullOrWhiteSpace(s))
                                    {
                                        status += "'" + s + "',";
                                    }
                                }
                                sb.Append("status in (" + status.TrimEnd(',') + ")");
                            }
                            else if (obj.Name == "proName")
                            {
                                #region  通过存货名称查到相关计划，然后再进行计划筛选
                                StringBuilder prosb = new StringBuilder();
                                prosb.Append("select DISTINCT plCode from V_ProductionPlan_products where proName ");
                                prosb.Append("like  '%" + obj.Value.ToString() + "%'");
                                var pTable = cmd.GetDataTable(prosb.ToString());
                                if (pTable.Rows.Count > 0)
                                {
                                    var plCodes = "";
                                    foreach (DataRow dr in pTable.Rows)
                                    {
                                        plCodes += "'" + dr[0].ToString() + "',";
                                    }
                                    sb.Append(" plCode in (" + plCodes.TrimEnd(',') + ") ");
                                }
                                #endregion 
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                #endregion

                var list = cmd.PageList("V_Allplans", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                getPlanRelationData(ref list);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取生产计划关联数据
        /// </summary>
        /// <param name="list"></param>
        private void getPlanRelationData(ref List<Dictionary<string, string>> list)
        {
            StringBuilder sb;
            for (int i = 0; i < list.Count; i++)
            {
                sb = new StringBuilder();
                sb.Append("select * from V_ProductionPlan_products where isdel=0");
                sb.Append(" and prlCode='" + list[i]["prlCode"].ToString() + "'");
                var datas = cmd.GetDataTable(sb.ToString());
                if (datas.Rows.Count > 0)
                {
                    List<string> pCode = new List<string>();
                    List<string> pName = new List<string>();
                    foreach (DataRow dr in datas.Rows)
                    {
                        if (!pCode.Contains(dr["proCode"].ToString()))
                        {
                            pCode.Add(dr["proCode"].ToString());
                            pName.Add(dr["proName"].ToString());
                        }
                        sb.Clear();
                        sb.Append("select * from V_PlanPaiChan_info where isdel=0 and ppId='" + dr["id"].ToString() + "' ");
                        var pgtable = cmd.GetDataTable(sb.ToString());
                        if (pgtable.Rows.Count > 0)
                            list[i]["isPaiGong"] = "1";
                        else
                            list[i]["isPaiGong"] = "0";
                    }
                    List<string> clist = new List<string>();
                    foreach (DataRow r in datas.Rows)
                    {
                        if (!clist.Contains(r["cuName"].ToString()))
                        {
                            clist.Add(r["cuName"].ToString());
                        }
                    }
                    list[i]["cuNames"] = String.Join(",", clist);
                }
            }
        }

        //获取计划的工艺名称
        private void getGYName(ref List<Dictionary<string, string>> list)
        {
            StringBuilder sb;
            for (int i = 0; i < list.Count; i++)
            {
                sb = new StringBuilder();
                if (!string.IsNullOrWhiteSpace(list[i]["cu_gy"]))
                {
                    sb.Append("select top 1 gyName from fun_products_gx where gyCode = '" + list[i]["cu_gy"].ToString() + "'");
                    var datas = cmd.GetDataTable(sb.ToString());
                    if (datas.Rows.Count > 0)
                    {
                        list[i]["cu_gyName"] = datas.Rows[0][0].ToString();
                    }
                }

            }
        }

        /// <summary>
        /// 获取生产计划报工不合格数
        /// </summary>
        /// <param name="list"></param>
        private void getPlannNum(ref List<Dictionary<string, string>> list)
        {
            StringBuilder sb;
            for (int i = 0; i < list.Count; i++)
            {
                #region  获取不合格数
                sb = new StringBuilder();
                sb.Append("select SUM(CONVERT(decimal(18,2),nNum)) nNum from pi_PlanBaogong_main where isDel=0");
                sb.Append(" and ppId='" + list[i]["id"].ToString() + "'");
                var datas = cmd.GetDataTable(sb.ToString());
                if (string.IsNullOrWhiteSpace(datas.Rows[0][0].ToString()))
                    list[i]["nNum"] = "0.00";
                else
                    list[i]["nNum"] = datas.Rows[0][0].ToString();

                #endregion
                #region 设置计划是否退料标识
                list[i]["isTuiLiao"] = "0";
                sb.Clear();
                sb.Append("select plCode from pi_PaiGong_material_main m where status = 'bl-in' and isdel = 0 ");
                datas = cmd.GetDataTable(sb.ToString());
                if (datas.Rows.Count > 0)
                {
                    foreach (DataRow s in datas.Rows)
                    {
                        if (s["plCode"].ToString().Contains(list[i]["id"].ToString()))
                        {
                            list[i]["isTuiLiao"] = "1";
                        }
                    }
                }
                #endregion
            }
        }
        /// <summary>
        /// 存货生产计划
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult ProductPlanList(string pageIndex, string pageSize, ref string pageCount, string condition,string types)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                var maxR = pcbll.getMaxRole();

                sb.Clear();
                sb.Append(" pStatus='pass' ");
                if (types == "zz")
                {
                    sb.Append(" and plType='P-ZhiZao' ");
                }
                else
                {
                    sb.Append(" and plType!='P-ZhiZao' ");
                }
                if (userLogin.UserInfo().isAdmin == 0 && !userLogin.UserInfo().powerRole.Equals(maxR))
                {
                    sb.Append(" and createuser='" + userLogin.UserInfo().userCode + "' ");
                }

                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    if (string.IsNullOrWhiteSpace(json["cStatus"].ToString()))
                    {
                        sb.Append(" and status in ('ps-prtpg-set', 'ps-dsc')");
                    }
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (obj.Name == "status")
                            {
                                continue;
                            }
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "cStatus")
                            {
                                var sArr = obj.Value.ToString().Split(',');
                                string status = "";
                                foreach (string s in sArr)
                                {
                                    if (!string.IsNullOrWhiteSpace(s))
                                    {
                                        status += "'" + s + "',";
                                    }
                                }
                                sb.Append("status in (" + status.TrimEnd(',') + ")");
                            }
                            else if (obj.Name == "gxCode" || obj.Name == "cgxCode")
                            {
                                sb.Append(obj.Name + "='" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }

                }
                var list = cmd.PageList("V_ProductionPlan_process", pageIndex, pageSize, sb.ToString(), "createtime desc,pLevel desc,plCode desc,gxNum", ref pageCount);
                CoutPaiGongDone(ref list);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 数据合计
        /// </summary>
        /// <param name="list"></param>
        private void CoutPaiGongDone(ref List<Dictionary<string, string>> list)
        {
            StringBuilder sb = new StringBuilder();
            string total = "0";
            for (int i = 0; i < list.Count; i++)
            {
                total = "0";
                string id = list[i]["proId"].ToString();
                sb.Clear();
                sb.Append("select isnull(sum(CONVERT(decimal(10,2),number)),0) num  from pi_PlanPaiGong_info");
                sb.Append(" where isdel=0 and ppid='" + id + "' and gxCode='" + list[i]["gxCode"].ToString() + "'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count < 1)
                {
                    total = "0";
                }
                else
                {
                    total = table.Rows[0][0].ToString();
                }
                list[i]["pgTotal"] = total;

                sb.Clear();
                sb.Append("select isnull(CONVERT(decimal(18,1),yNum),'0') num from pi_PlanBaogong_main where pKey in");
                sb.Append("(select tpCode from pi_PlanPaiGong_info where ppid in (select id from");
                sb.Append(" pi_ProductionPlan_products where id=" + id + " ))");
                sb.Append(" and isdel=0 and gxCode='" + list[i]["gxCode"] + "'");
                table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count < 1)
                {
                    list[i]["bgNum"] = "0";
                }
                else
                {
                    list[i]["bgNum"] = table.Rows[0][0].ToString();
                }
            }
        }
        /// <summary>
        /// 根据计划编码获取计划存货
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult PlanProductByPlCode(string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_ProductionPlan_products where prlCode='" + plCode + "'");
                sb.Append(" and isdel=0");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据计划编码获取计划报工
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult PlanBaoGongByPlCode(string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select *,'' total from V_Plan_BaoGong_Sub where prlCode='" + plCode + "'");
                sb.Append(" and isdel=0 order by orderNum ");
                var table = cmd.GetDataTable(sb.ToString());
                #region 统计各工序报工数量
                var gx = "";//工序编码
                double totaly = 0,totaln=0;//各工序合计报工合格数/不合格数
                for (var i =0;i<table.Rows.Count;i++)
                {
                    if (i == 0)
                    {
                        gx = table.Rows[i]["gxCode"].ToString();//第一行
                        totaly += Convert.ToDouble(table.Rows[i]["yNum"].ToString());
                        totaln += Convert.ToDouble(table.Rows[i]["nNum"].ToString());
                    }
                    else
                    {
                        if (table.Rows[i]["gxCode"].ToString().Equals(gx))
                        {
                            //第二行开始，如果工序和上一行的工序一样，数量累加
                            totaly += Convert.ToDouble(table.Rows[i]["yNum"].ToString());
                            totaln += Convert.ToDouble(table.Rows[i]["nNum"].ToString());
                            gx = table.Rows[i]["gxCode"].ToString();
                        }
                        else
                        {
                            //第二行开始，如果工序和上一行的工序不一样，在上一行（即上个工序最后一行记录报工总数）
                            table.Rows[i-1]["total"] = totaly + "/" + totaln;

                            totaly = 0; totaln = 0;
                            totaly += Convert.ToDouble(table.Rows[i]["yNum"].ToString());
                            totaln += Convert.ToDouble(table.Rows[i]["nNum"].ToString());
                            gx = table.Rows[i]["gxCode"].ToString();

                        }
                    }

                    //如果是最后一行，在本行记录报工总数
                    if (i == table.Rows.Count - 1)
                    {
                        table.Rows[i]["total"] = totaly + "/" + totaln;
                    }

                }
                #endregion
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据计划编码获取计划条码
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        //public ReturnResult PlanBarByPlCode(string plCode, string rowNo)
        public ReturnResult PlanBarByPlCode(string prlCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                //sb.Append("select * from V_BarCode_Info where planCode='" + plCode + "'");
                sb.Append("select top 10 m.planCode,m.proWeight,m.barStatusName,b.* from V_BarCode_Info m ");
                sb.Append("inner join bar_ProductBarCode_Sub_info b on b.barCode = m.barCode ");
                //sb.Append("where barStatus !='bar-drop' and planCode='" + plCode + "' and plRowNo='" + rowNo + "'");
                sb.Append("where barStatus !='bar-drop' and planCode='" + prlCode + "' ");
                sb.Append("order by m.id desc ");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据计划编码获取计划工艺
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult PlanProcessByPlCode(string plCode, string type)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (type.Contains("包装"))
                {
                    sb.Append("select proCode,proName,spec,cu_yanse,cu_shangbiao,gxName,gxName gyName ");
                    sb.Append("from V_ProductionPlan_process where prlCode='" + plCode + "' ");
                }
                else
                {
                    sb.Append("select distinct i.proName,i.spec,pr.cgxName gxName,g.gyName,p.* from  ");
                    sb.Append("pi_ProductionPlan_products p inner join fun_Inventory_Info i on p.proCode=i.proCode ");
                    sb.Append(" inner join fun_products_gx g on g.gyCode=p.cu_gy ");
                    sb.Append(" inner join fun_GxPrice_info pr on pr.cgxCode=g.gxCode and pr.isDel=0 ");
                    sb.Append(" where p.isdel=0 and prlCode='" + plCode + "' ");
                }

                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据计划存货id获取数据信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ReturnResult GetPlanInfoById(string pids, string gids)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_ProductionPlan_process where ");
                sb.Append(" id in(" + gids + ")");
                var table = cmd.GetDataTable(sb.ToString());
                var dic = new Dictionary<string, string>();
                string proInfo = "", plCode = "";
                foreach (DataRow r in table.Rows)
                {
                    #region 存货信息
                    string n = string.Format("{0}({1})", r["proName"].ToString(), r["proCode"].ToString());
                    if (string.IsNullOrWhiteSpace(proInfo))
                    {
                        proInfo = n + ",";
                    }
                    else
                    {
                        var arr = proInfo.Split(',');
                        bool isAdd = false;
                        foreach (string s in arr)
                        {
                            if (!string.IsNullOrWhiteSpace(s))
                            {
                                if (n != s)
                                {
                                    isAdd = true; break;
                                }
                            }
                        }
                        //bool isAdd=true;
                        //foreach (string s in arr)
                        //{
                        //    if (string.IsNullOrWhiteSpace(s))
                        //    {
                        //        if (n == s)
                        //        {
                        //            isAdd = false;break;
                        //        }
                        //    }
                        //}
                        if (isAdd)
                        {
                            proInfo += n + ",";
                        }
                    }
                    #endregion

                    #region 计划
                    n = r["plCode"].ToString();
                    if (string.IsNullOrWhiteSpace(plCode))
                    {
                        plCode = n + ",";
                    }
                    else
                    {
                        var arr = plCode.Split(',');
                        bool isAdd = false;
                        foreach (string s in arr)
                        {
                            if (!string.IsNullOrWhiteSpace(s))
                            {
                                if (n != s)
                                {
                                    isAdd = true; break;
                                }
                            }
                        }
                        //bool isAdd = true;
                        //foreach (string s in arr)
                        //{
                        //    if (string.IsNullOrWhiteSpace(s))
                        //    {
                        //        if (n == s)
                        //        {
                        //            isAdd = false; break;
                        //        }
                        //    }
                        //}
                        if (isAdd)
                        {
                            plCode += n + ",";
                        }
                    }
                    #endregion
                }
                dic["proNames"] = proInfo.TrimEnd(',');
                dic["ids"] = plCode.TrimEnd(',');

                rsl.Data = dic;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }

        /// <summary>
        /// 生产计划工序数据列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getPlanProcessList(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_PlanProcess_info where isdel=0");
                sb.Append(" and plCode='" + json["plCode"] + "' and proCode='" + json["proCode"] + "'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据计划编码获取计划数据信息
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <returns></returns>
        public ReturnResult getPlanInfoByCode(string plCode, string prlCode, string keyCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(plCode))
                {
                    rsl.Message = "计划编码为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_ProductPlan_info where ");
                sb.Append("plCode='" + plCode + "'");
                var list = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                //getPlanRelationData(ref list);

                sb.Clear();
                sb.Append("select id dataId,* from V_ProductionPlan_products where prlCode='" + prlCode + "'");
                sb.Append(" and isdel=0");
                var pList = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                this.getPlanNum(pList[0]["plType"], ref pList);

                foreach (var item in pList)
                {
                    sb.Clear();
                    sb.Append("select * from pi_PaiGong_sub where ppId='" + item["dataId"] + "' and isdel=0 ");
                    var pgtable = cmd.GetDataTable(sb.ToString());
                    if (pgtable.Rows.Count > 0)
                        item["isPaiGong"] = "1";
                    else
                        item["isPaiGong"] = "0";
                }

                Dictionary<string, object> d = new Dictionary<string, object>();
                d["plan"] = list;
                d["products"] = pList;
                string key = userLogin.UserInfo().userCode + keyCode;
                Tools.Cache.SetCache(key, JsonConvert.SerializeObject(pList));
                rsl.Data = d;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据计划编码获取计划生产工艺
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult GetPlanGx(string plCode, string order, string rowNo)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(plCode))
                {
                    rsl.Message = "计划编码为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from pi_ProductionPlan_process where ");
                sb.Append("plCode='" + plCode + "' and orderCode='" + order + "' and rowNo='" + rowNo + "'");
                var data = cmd.GetDataTable(sb.ToString());
                var dList = new List<Dictionary<string, string>>();
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    var gxCode = data.Rows[i]["gxCode"].ToString();
                    var dr = data.Select("parentCode='" + gxCode + "'");
                    if (dr.Length < 1)
                    {
                        var d = new Dictionary<string, string>();
                        d["gxCode"] = gxCode;
                        dList.Add(d);
                    }

                }
                rsl.Data = dList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 生产备货存货添加
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult AddProductBH(string proCode, string cuCodes, string datalist)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                sb.Append("select * from fun_Inventory_Info ");
                sb.Append("where proCode='" + proCode + "'");
                var pTable = cmd.GetDataTable(sb.ToString());
                if (pTable.Rows.Count < 1)
                {
                    rsl.Message = "存货不存在";
                    return rsl;
                }
                var cuArr = cuCodes.Split(',');
                Dictionary<string, string> p;
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                foreach (string r in cuArr)
                {
                    if (!string.IsNullOrWhiteSpace(r))
                    {
                        sb.Clear();
                        sb.Append("select * from fun_Customs_info where cuCode='" + r + "'");
                        sb.Append(" and dataType='Cu'");
                        var cuTable = cmd.GetDataTable(sb.ToString());
                        p = new Dictionary<string, string>();
                        p["proCode"] = pTable.Rows[0]["proCode"].ToString();
                        p["proName"] = pTable.Rows[0]["proName"].ToString();
                        p["cuName"] = cuTable.Rows[0]["cuName"].ToString();
                        p["cuCode"] = cuTable.Rows[0]["cuCode"].ToString();
                        p["payDate"] = getNowDate(2);
                        p["dataId"] = Guid.NewGuid().ToString().Replace("-", "");
                        list.Add(p);
                    }
                }
                //     rsl=this.TempSaleInfo(JsonConvert.SerializeObject(list));

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 删除备货生产计划保存数据
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <returns></returns>
        public ReturnResult DelPlanProduct(string dataId, string keyCode)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                StringBuilder sb = new StringBuilder();
                if (IsNum(dataId))
                {
                    #region 删除数据库数据
                    sb.Append("select * from pi_ProductionPlan_products where id=" + dataId);
                    var table = cmd.GetDataTable(sb.ToString());
                    string p_num = table.Rows[0]["number"].ToString();
                    string plCode = table.Rows[0]["plCode"].ToString();
                    DbProductionPlanPro pro = new DbProductionPlanPro();
                    pro.isdel = 1;
                    pro.delDate = getNow();
                    pro.delUser = userLogin.UserInfo().userCode;
                    pro.id = Convert.ToInt32(dataId);
                    oper = new OperateModel();
                    oper.Data = pro;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    operList.Add(oper);
                    #region 计划关联工序
                    DbPlanGongXu pgx = new DbPlanGongXu();
                    pgx.proCode = table.Rows[0]["proCode"].ToString();
                    pgx.plCode = plCode;
                    pgx.rowNo = table.Rows[0]["rowNo"].ToString();

                    oper = new OperateModel();
                    oper.Data = pgx;
                    oper.Types = OperateModel.OperateType.Delete;
                    operList.Add(oper);
                    #endregion

                    #region 主计划信息
                    sb.Clear();
                    sb.Append("select * from pi_ProductionPlan_info where ");
                    sb.Append("plCode='" + table.Rows[0]["plCode"].ToString() + "'");
                    table = cmd.GetDataTable(sb.ToString());
                    DbProductionPlan p = new DbProductionPlan();
                    p.id = int.Parse(table.Rows[0]["id"].ToString());
                    p.number = (double.Parse(table.Rows[0]["number"].ToString()) - double.Parse(p_num)).ToString();
                    pro.id = Convert.ToInt32(dataId);
                    oper = new OperateModel();
                    oper.Data = p;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    operList.Add(oper);
                    #endregion

                    #endregion
                }
                string key = userLogin.UserInfo().userCode + keyCode;
                var data = Tools.Cache.GetCache(key);
                if (data != null)
                {
                    var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(data.ToString());
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i]["dataId"] == dataId)
                        {
                            list.Remove(list[i]);
                            break;
                        }
                    }
                    Tools.Cache.SetCache(key, JsonConvert.SerializeObject(list));
                }
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        
        /// <summary>
        /// 删除备货要货单(临时)数据
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <returns></returns>
        public ReturnResult DelProAsk(string dataId, string keyCode)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                StringBuilder sb = new StringBuilder();
                string key = userLogin.UserInfo().userCode + keyCode;
                var data = Tools.Cache.GetCache(key);
                if (data != null)
                {
                    var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(data.ToString());
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i]["dataId"] == dataId)
                        {
                            list.Remove(list[i]);
                            break;
                        }
                    }
                    Tools.Cache.SetCache(key, JsonConvert.SerializeObject(list));
                }
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除生产计划
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <returns></returns>
        public ReturnResult DelPlan(string plCode, string rowNo, string prlCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                #region 判断计划是否已派工
                StringBuilder sb = new StringBuilder();
                sb.Append("select pg.ppId,p.plCode from pi_PlanPaiGong_info pg ");
                sb.Append("inner join pi_ProductionPlan_products p on p.id = pg.ppId ");
                sb.Append("where pg.isDel = 0 and p.isdel = 0 and p.prlCode='" + prlCode + "'");
                var pgTable = cmd.GetDataTable(sb.ToString());

                if (pgTable.Rows.Count > 0)
                {
                    rsl.Message = "此计划已派工，暂不支持删除计划";
                    return rsl;
                }
                #endregion

                #region 删除方法
                DbProductionPlanPro pro = new DbProductionPlanPro();
                pro.isdel = 1;
                pro.delDate = getNow();
                pro.delUser = userLogin.UserInfo().userCode;
                pro.prlCode = prlCode;
                oper = new OperateModel();
                oper.Data = pro;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "prlCode";
                operList.Add(oper);

                DbPlanGongXu gx = new DbPlanGongXu();
                gx.plCode = plCode;
                gx.rowNo = rowNo;
                oper = new OperateModel();
                oper.Data = gx;
                oper.Types = OperateModel.OperateType.Delete;
                oper.Conditions = "plCode,rowNo";
                operList.Add(oper);

                #endregion

                rsl = cmd.MoreUpdate(operList);

                #region 如果子表都删完了，主表也删除
                if (rsl.Result)
                {
                    operList = new List<OperateModel>();
                    sb.Clear();
                    sb.Append("select count(*) from pi_ProductionPlan_products where isdel=0 and plCode = '" + plCode + "'");
                    var pTable = cmd.GetDataTable(sb.ToString());
                    if (pTable.Rows[0][0].ToString() == "0")
                    {
                        DbProductionPlan plan = new DbProductionPlan();
                        plan.plCode = plCode;
                        plan.delDate = getNow();
                        plan.delUser = userLogin.UserInfo().userCode;
                        plan.isdel = 1;
                        oper = new OperateModel();
                        oper.Data = plan;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "plCode";
                        operList.Add(oper);

                        rsl = cmd.MoreUpdate(operList);
                    }

                }
                #endregion
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        //根据id删除要货单
        public ReturnResult DelAsk(int id)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                StringBuilder sb = new StringBuilder();
                #region 判断要货单是否已创建计划
                sb.Append("select * from pi_ProductionPlan_products where isdel = 0 and  aid =" + id);
                var pgTable = cmd.GetDataTable(sb.ToString());

                if (pgTable.Rows.Count > 0)
                {
                    rsl.Message = "此要货单已创建计划，暂不支持删除";
                    return rsl;
                }
                #endregion

                #region 删除
                DbProAsk pro = new DbProAsk();
                pro.isdel = 1;
                pro.deltime = getNow();
                pro.delUser = userLogin.UserInfo().userCode;
                pro.id = id;
                oper = new OperateModel();
                oper.Data = pro;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                operList.Add(oper);
                #endregion

                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 保存选择报工人员
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="yNum"></param>
        /// <param name="nNum"></param>
        /// <returns></returns>
        public ReturnResult DoSaveBaoGongUser(string datas, string yNum, string nNum, string hDate)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(datas))
                {
                    rsl.Message = "没有数据";
                    return rsl;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(yNum))
                    {
                        yNum = "0";
                    }
                    if (string.IsNullOrWhiteSpace(nNum))
                    {
                        nNum = "0";
                    }

                    StringBuilder sb = new StringBuilder();
                    sb.Append("select * from sys_users_info where isdel=0");
                    var uTable = cmd.GetDataTable(sb.ToString());
                    var arr = datas.Split(',');
                    int uCount = 1;
                    foreach (string s in arr)
                    {
                        if (!string.IsNullOrWhiteSpace(s))
                        {
                            if (s.IndexOf("U-") > -1)
                            {
                                uCount++;
                            }
                        }
                    }
                    #region 除不尽问题处理
                    double defNumber = (int)((double.Parse(yNum) / (uCount - 1)) * 100) / 100.0;//实际每个人平均分到的数量（不进位）
                    double temyTotal = Math.Round(defNumber * (uCount - 1), 2);   //实际报工合格数总和
                    double temcY = Math.Round(double.Parse(yNum) - temyTotal, 2);//差值

                    double defnNumber = (int)((double.Parse(nNum) / (uCount - 1)) * 100) / 100.0;//实际每个人平均分到的数量（不进位）
                    double temnTotal = Math.Round(defnNumber * (uCount - 1), 2);   //实际报工不合格数总和
                    double temcN = Math.Round(double.Parse(nNum) - temnTotal, 2);//差值

                    //yNum = (double.Parse(yNum) / (uCount - 1)).ToString("F2");
                    //nNum = (double.Parse(nNum) / (uCount - 1)).ToString("F2");

                    #endregion

                    List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                    foreach (string s in arr)
                    {
                        if (!string.IsNullOrWhiteSpace(s))
                        {
                            if (s.IndexOf("U-") > -1)
                            {
                                string nstr = s.Replace("U-", "");
                                var d = new Dictionary<string, string>();
                                var dr = uTable.Select("userCode='" + nstr + "'");
                                if (dr.Length > 0)
                                {
                                    d["userName"] = dr[0]["userName"].ToString();
                                }
                                else
                                {
                                    d["userName"] = nstr;
                                }
                                d["userCode"] = nstr;
                                #region 除不尽问题处理
                                //d["yNum"] = yNum;
                                //d["nNum"] = nNum;
                                if (temcY > 0)
                                {
                                    d["yNum"] = (defNumber + 0.01).ToString();
                                    temcY -= 0.01;
                                }
                                else
                                {
                                    d["yNum"] = defNumber.ToString();
                                }
                                if (temcN > 0)
                                {
                                    d["nNum"] = (defnNumber + 0.01).ToString();
                                    temcN -= 0.01;
                                }
                                else
                                {
                                    d["nNum"] = defnNumber.ToString();
                                }

                                #endregion
                                if (string.IsNullOrWhiteSpace(hDate))
                                {
                                    hDate = getNowDate();
                                }
                                d["happenDate"] = hDate;
                                list.Add(d);
                            }
                        }
                    }

                    rsl.Result = true;
                    rsl.Data = JsonConvert.SerializeObject(list);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据编码获取卷材占用层信息计划信息
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="ceng">使用层</param>
        /// <returns></returns>
        public ReturnResult getJuanPlanByCode(string plCode, string ceng)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select customCode,customName,c_caizhi");
                sb.Append(" from V_ProductPlan_info ");
                sb.Append(" where plCode='" + plCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["customCode"] = table.Rows[0]["customCode"].ToString();
                dic["customName"] = table.Rows[0]["customName"].ToString();
                var czJson = JsonConvert.DeserializeObject<JObject>(table.Rows[0]["c_caizhi"].ToString());
                foreach (JProperty jp in czJson.Properties())
                {
                    var cn = jp.Name.Split('-');
                    if (cn[1].ToString().Trim() == Convert.ToString(int.Parse(ceng) - 1))
                    {
                        dic[cn[0]] = jp.Value.ToString();
                    }
                }
                sb.Clear();
                sb.Append("select width,thickness from fun_Inventory_Info");
                sb.Append(" where proCode='" + dic["proCode"] + "'");
                table = cmd.GetDataTable(sb.ToString());
                dic["width"] = table.Rows[0]["width"].ToString();
                dic["thickness"] = table.Rows[0]["thickness"].ToString();
                rsl.Data = dic;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 计划工序
        /// </summary>
        /// <param name="conditions">数据条件</param>
        /// <returns></returns>
        public ReturnResult GetPlanGongXu(string conditions)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(conditions);
                StringBuilder sb = new StringBuilder();
                sb.Append("select cCode gxCode,cName gxName,orderNum,'0' cgx,'' gxPrice ");
                sb.Append(" from fun_CommonData_Info where isdel=0 and status='Y' and cType='Gx'");
                sb.Append(" and cCode is not null and cCode !=''");
                var gxTable = cmd.GetDataTable(sb.ToString());

                if (!string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {

                    sb.Clear();
                    sb.Append("select * from pi_ProductionPlan_process where plCode='" + json["plCode"] + "'");
                    sb.Append(" and proCode='" + json["proCode"].ToString() + "'");
                    var pGxTable = cmd.GetDataTable(sb.ToString());
                    if (pGxTable.Rows.Count < 1)
                    {
                        sb.Clear();
                        sb.Append("select * from fun_products_gx ");
                        sb.Append("where proCode='" + json["proCode"].ToString() + "'");//品类
                        pGxTable = cmd.GetDataTable(sb.ToString());
                    }

                    for (int i = 0; i < gxTable.Rows.Count; i++)
                    {
                        string gxCode = gxTable.Rows[i]["gxCode"].ToString();
                        var dr = pGxTable.Select("gxCode='" + gxCode + "'");
                        if (dr.Length > 0)
                        {
                            gxTable.Rows[i]["cgx"] = "1";
                            gxTable.Rows[i]["orderNum"] = dr[0]["gxOrder"].ToString();
                        }

                    }
                }
                rsl.Data = cmd.TableToDictionary(gxTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 计划工序具体字段数据
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="gxCode">工序编码</param>
        /// <returns></returns>
        public ReturnResult PlanGongXuData(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select gxIStart,gxContents from pi_ProductionPlan_process ");
                sb.Append(" where id=" + dataId);
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 更改计划临时存货数据信息
        /// </summary>
        /// <param name="timeKey"></param>
        /// <param name="proCode"></param>
        /// <param name="uValue"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public ReturnResult EditPlanTempData(string timeKey, string proCode, string uValue, string number)
        {
            rsl = new ReturnResult();
            try
            {
                var table = (DataTable)Tools.Cache.GetCache(timeKey);
                if (table == null || table.Rows.Count < 1)
                {
                    rsl.Message = "没有要修改的数据";
                    return rsl;
                }
                foreach (DataRow r in table.Rows)
                {
                    if (proCode == r["proCode"].ToString())
                    {
                        r.BeginEdit();
                        if (!string.IsNullOrWhiteSpace(uValue))
                        {
                            r["unit"] = uValue;
                        }
                        if (!string.IsNullOrWhiteSpace(number))
                        {
                            r["number"] = number;
                        }
                        r.EndEdit();
                        break;
                    }
                }
                Tools.Cache.SetCache(timeKey, table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除计划临时存货数据信息
        /// </summary>
        /// <param name="timeKey"></param>
        /// <param name="proCode"></param>
        /// <returns></returns>
        public ReturnResult DelPlanTempData(string timeKey, string proCode, string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                var table = (DataTable)Tools.Cache.GetCache(timeKey);

                if (table == null || table.Rows.Count < 1)
                {
                    rsl.Message = "没有要删除的数据";
                    return rsl;
                }
                foreach (DataRow r in table.Rows)
                {
                    if (proCode == r["proCode"].ToString())
                    {
                        r.Delete();
                        break;
                    }
                }
                Tools.Cache.SetCache(timeKey, table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 保存工序生产要求表单数据
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SavePlanGongXu(string datas)
        {
            rsl = new ReturnResult();
            try
            {

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 获取派工单详情
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetProductionPlanDo(string pageIndex, string pageSize, ref string pageCount, string condition)
        {

            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" baseCode='" + userLogin.UserInfo().baseCode + "' and isdel=0 ");
                if (userLogin.UserInfo().isAdmin != 1)
                {
                    #region 非管理员权限
                    string sql = "select * from pi_GongXuUser_set where usCode='" + userLogin.UserInfo().userCode + "'";
                    var table = cmd.GetDataTable(sql);//人员管理工序数据查询
                    if (table.Rows.Count > 0)
                    {
                        string gx = "";
                        foreach (DataRow r in table.Rows)
                        {
                            gx += "'" + r["GongXu"].ToString() + "',";
                        }
                        sb.Append(" and process in(" + gx.TrimEnd(',') + ") and status='pro-doing' ");
                    }
                    else
                    {

                        sb.Append("1>2");
                    }
                    #endregion
                }
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        {
                            sb.Append(" and ");
                        }
                        if (obj.Name.ToString().Trim() == "status")
                        {
                            sb.Append(" status='" + json["status"].ToString() + "' ");
                        }
                        else if (obj.Name.ToString().Trim() == "process")
                        {
                            sb.Append(" process='" + json["process"].ToString() + "' ");
                        }
                        else
                        {
                            sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                        }

                    }
                }
                var list = cmd.PageList<ViewProductionPlanDo>("V_ProductionPlanDo", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = this.JZBarCodesCount(list);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }
        private List<ViewProductionPlanDo> JZBarCodesCount(List<ViewProductionPlanDo> list)
        {
            StringBuilder sb = new StringBuilder();
            string plCodes = "";
            for (int x = 0; x < list.Count; x++)
            {
                plCodes += "'" + list[x].plCode + "',";
            }
            sb.Append("select gxCode,gxOrder,plCode from pi_ProductionPlan_process where plCode ");
            sb.Append("in(" + plCodes.TrimEnd(',') + ")");
            sb.Append(" order by gxOrder");
            var proceeTable = cmd.GetDataTable(sb.ToString());
            for (int x = 0; x < list.Count; x++)
            {
                sb.Clear();
                if (list[x].ptType != "scm")
                {
                    var dr = proceeTable.Select("plCode='" + list[x].plCode + "'");

                    if (dr.Length > 0)
                    {
                        list[x].plCode = dr[0]["plCode"].ToString();
                        string bGx = "";
                        #region 获取上一道工序编码
                        for (int i = 0; i < dr.Length; i++)
                        {
                            if (dr[i]["gxCode"].ToString() == list[x].process)
                            {
                                if (i > 0)
                                {
                                    bGx = dr[i - 1]["gxCode"].ToString();
                                    break;
                                }
                            }
                        }
                        #endregion
                        if (!string.IsNullOrWhiteSpace(bGx))
                        {
                            #region 存在上道工序
                            sb.Clear();
                            sb.Append("select count(barCode) from bar_ProductBarCode_info where ");
                            sb.Append("planCode='" + dr[0]["plCode"].ToString() + "' and status='Y'");
                            sb.Append(" and gxCode='" + bGx + "' and barStatus='need-out' ");
                            var bTable = cmd.GetDataTable(sb.ToString());
                            if (bTable.Rows.Count > 0)
                            {
                                list[x].barCount = bTable.Rows[0][0].ToString();
                            }
                            #endregion
                        }
                        else
                        {
                            #region 如果没有工序 则查询占用数
                            sb.Clear();
                            sb.Append("select count(po.barCode) barCount from pi_ProductOccupy_info po");
                            sb.Append(" inner join bar_ProductBarCode_info b on po.barCode=b.barCode ");
                            sb.Append("where po.plCode='" + dr[0]["plCode"].ToString() + "' and b.barStatus='need-out'");
                            var table = cmd.GetDataTable(sb.ToString());
                            if (table.Rows.Count > 0)
                            {
                                list[x].barCount = table.Rows[0][0].ToString();
                            }
                            #endregion
                        }
                    }
                    if (string.IsNullOrWhiteSpace(list[x].barCount))
                    {
                        list[x].barCount = "0";
                    }
                }

            }
            return list;
        }
        /// <summary>
        /// 更改工序序号
        /// </summary>
        /// <param name="dataId"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ReturnResult EditGongXuOrder(string dataId, string value)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(dataId) || string.IsNullOrWhiteSpace(value))
                {
                    rsl.Message = "关键参数不允许为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("update pi_ProductionPlan_process set gxOrder=" + value);
                sb.Append(" where id=" + dataId);
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 更改派工顺序
        /// </summary>
        /// <param name="dataId"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ReturnResult EditPaiGongOrder(string dataId, string value)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(dataId) || string.IsNullOrWhiteSpace(value))
                {
                    rsl.Message = "关键参数不允许为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("update pi_ProductionPlan_do_list set orderNo=" + value);
                sb.Append(" where id=" + dataId);
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 生产计划完成
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult FinishPlan(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                rsl = this.ChanagePlanStatus(json["plCode"].ToString(), "do-finish", "计划结束", json["userCode"].ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 检验是否是最后一道工序
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="gxCode">当前工序编码</param>
        /// <returns></returns>
        public bool isLastGongXu(string plCode, string gxCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from pi_ProductionPlan_process where plCode='" + plCode + "'");
            sb.Append("order by gxOrder asc");
            var table = cmd.GetDataTable(sb.ToString());
            bool isLast = false;
            if (table.Rows.Count > 0)
            {
                if (table.Rows[table.Rows.Count - 1]["gxCode"].ToString() == gxCode)
                {
                    isLast = true;
                }

            }
            return isLast;
        }
        /// <summary>
        /// 生产检验
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getProductCheckInfo(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {

                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" 1=1 ");
                sb = CreateSelectCondition(sb, condition);

                var list = cmd.PageList<ViewProductCheck>("V_ProductCheck_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 创建外部采购申请单
        /// </summary>
        /// <returns></returns>
        public ReturnResult CreatePurchasesOrder(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var data = JsonConvert.DeserializeObject<DbPurchases>(datas);
                data.createtime = getNow();
                data.createuser = userLogin.UserInfo().userCode;
                data.status = "Y";
                ////此处需要填写调取U8生成采购订单接口
                data.relationOrder = "";//填写U8回传的采购订单号；
                rsl = cmd.Add(data);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        public ReturnResult GetPlanPaiGong(string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                List<string> list = new List<string>(plCode.Split(','));
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from pi_ProductionPlan_do_list ");
                for (int i = 0; i < list.Count; i++)
                {
                    if (i == 0)
                    {
                        sb.Append("where ptCode='" + list[i] + "'");
                    }
                    else
                    {
                        sb.Append(" or ptCode='" + list[i].ToString() + "'");
                    }
                }

                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Result = true;
                    rsl.Data = cmd.TableToDictionary(table);
                }
                else
                {
                    rsl.Message = "没有数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 保存计划派工信息
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult savePaiGongInfo(string plCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            StringBuilder sb = new StringBuilder();
            try
            {


                DbProductionPlan plan = new DbProductionPlan();
                plan.plCode = plCode;
                plan.status = "pro-doing";
                oper = new OperateModel();
                oper.Data = plan;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "plCode";
                operList.Add(oper);
                string sql = "select * from pi_ProductionPlan_process where plCode='" + plCode + "'";
                var table = cmd.GetDataTable(sql);
                sql = "select * from V_ProductPlan_info where plCode='" + plCode + "'";
                var mTable = cmd.GetDataTable(sql);
                foreach (DataRow r in table.Rows)
                {
                    string pCode = CreateCodeInfo("D", "派工单工号", 4);
                    #region 创建派工单子表
                    DbProductionPlanDoList dl = new DbProductionPlanDoList();
                    dl.plCode = plCode;
                    dl.ptCode = pCode;
                    dl.status = "ING";
                    dl.gxCode = r["gxCode"].ToString();
                    oper = new OperateModel();
                    oper.Data = dl;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                    #endregion

                    #region 派工单主表
                    DbProductionPlanDo pl = new DbProductionPlanDo();
                    pl.createtime = getNow();
                    pl.proCode = mTable.Rows[0]["proCode"].ToString();
                    pl.thickness = mTable.Rows[0]["thickness"].ToString();
                    pl.createuser = userLogin.UserInfo().userCode;
                    pl.plCode = plCode;
                    if (r["gxContents"] == null || string.IsNullOrWhiteSpace(r["gxContents"].ToString()))
                    {
                        rsl.Message = "工序信息未设置：" + r["gxCode"].ToString();
                        return rsl;
                    }
                    //  var mList = JsonConvert.DeserializeObject<JObject>(r["gxContents"].ToString());

                    pl.ptCode = pCode;
                    pl.ptType = "sjczd";
                    pl.process = r["gxCode"].ToString();
                    pl.status = "pro-doing";

                    oper = new OperateModel();
                    oper.Data = pl;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                    #endregion

                    #region 更改计划工序状态

                    #endregion

                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }




            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取U8销售数据
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="saleId"></param>
        /// <param name="saleCode"></param>
        /// <returns></returns>
        public ReturnResult getSalesInfo(string condition, string saleId, string saleCode)
        {
            rsl = new ReturnResult();
            CuDbHelper cuDb = new CuDbHelper();
            try
            {
                StringBuilder sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                string orType = "";
                //var cus = "";
                //var maxR = pcbll.getMaxRole();

                #region 获取当前登陆人负责的销售客户 已注释
                //sb.Append("select groupCode from fun_Users_gangwei where dType = 'CuMan' and cmType = 'xs' and userCode = '" + userLogin.UserInfo().userCode + "'");
                //var cTable = cmd.GetDataTable(sb.ToString());
                //foreach (DataRow dr in cTable.Rows)
                //{
                //    cus += "'" + dr["groupCode"].ToString() + "',";
                //}
                //if (string.IsNullOrWhiteSpace(cus) && userLogin.UserInfo().isAdmin != 1 && !userLogin.UserInfo().powerRole.Equals(maxR) )
                //{
                //    return rsl;
                //}
                #endregion

                #region 销售订单列表
                sb.Clear();
                sb.Append("select p.cInvStd spec,Convert(decimal(18,2),d.iQuantity) number,p.cComUnitCode unit,p.cInvDefine2 cu_xianggui,");
                sb.Append("m.cCusCode cuCode,m.cCusName cuName,d.cSOCode orderCode,d.cDefine30 cu_diaopai,d.cInvCode proCode,p.cInvName proName,");
                sb.Append("CONVERT(varchar(10), dPreDate, 120 ) payDate,d.AutoID,d.iRowNo rowNO,d.cFree3 cu_shangbiao,d.cFree1 cu_yanse, ");
                sb.Append("d.cDefine28 cu_baozhuangfangshi ,d.cFree4 cu_baozhuang,cFree2 cu_guohao,");
                sb.Append("ps.cPersonName,mc.cComUnitName,d.cDefine31 cu_neibaozhuangyq,d.cDefine32 cu_zhuangxiangyq,");
                sb.Append("cDefine33 cu_cunhuoweizhi,cDefine24 cu_fahuolaiyuan,p.cInvCCode typeCode,d.cMemo memo ,d.AutoID isosid ");//iSOsID->AutoID  s.fhNum,
                sb.Append(" from SO_SODetails d inner join Inventory p on d.cInvCode=p.cInvCode");
                sb.Append(" inner join SO_SOMain m on d.cSOCode=m.cSOCode ");
                //if (userLogin.UserInfo().isAdmin != 1 && !userLogin.UserInfo().powerRole.Equals(maxR) )
                //{
                //    sb.Append("and m.cCusCode in (" + cus.TrimEnd(',') + ") ");
                //}
                sb.Append(" left join Person ps on m.cPersonCode=ps.cPersonCode  ");
                sb.Append(" inner join ComputationUnit mc on p.cComUnitCode=mc.cComunitCode ");
                //   sb.Append("inner join ComputationUnit cc on cc.cComunitCode=d.cUnitID");
                //sb.Append("left join (select isnull(convert(decimal(18,2),iQuantity),0) fhNum,iSOsID  from SaleBillVouchs  ) s on s.iSOsID =d.AutoID  ");
                sb.Append(" where d.cSCloser is null ");//m.iStatus = 1 and
                #region 检索条件
                if (!string.IsNullOrWhiteSpace(orType))
                {
                    sb.Append("and m.cSTCode in (" + orType + ")");
                }
                if (!string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                {
                    sb.Append("and convert(datetime,dPreDate, 20)" + " >='" + json["sDate"].ToString() + "' ");
                }
                if (!string.IsNullOrWhiteSpace(json["eDate"].ToString()))
                {//结束时间
                    sb.Append("and convert(datetime,dPreDate, 20)" + "<= '" + json["eDate"].ToString() + "' ");
                }

                if (!string.IsNullOrWhiteSpace(json["cSOCode"].ToString()))
                {
                    sb.Append(" and  d.cSOCode  like '%" + json["cSOCode"].ToString().Trim() + "%' ");
                }
                if (!string.IsNullOrWhiteSpace(json["customName"].ToString()))
                {
                    sb.Append(" and  m.cCusName  like '%" + json["customName"].ToString().Trim() + "%' ");
                }
                if (!string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    sb.Append(" and  d.cInvCode  like '%" + json["proCode"].ToString().Trim() + "%' ");
                }
                if (!string.IsNullOrWhiteSpace(json["proName"].ToString()))
                {
                    sb.Append(" and  p.cInvName  like '%" + json["proName"].ToString().Trim() + "%' ");
                }
                #region 已注释
                //if (!string.IsNullOrWhiteSpace(condition))
                //{
                //    foreach (JProperty obj in json.Properties())
                //    {
                //        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                //        {
                //            if (obj.Name.ToString().Equals("sDate"))
                //            {
                //                sb.Append("and convert(datetime,dPreDate, 20)" + " >='" + json["sDate"].ToString() + "' ");
                //            }
                //            else if (obj.Name.ToString().Equals("eDate"))
                //            {//结束时间
                //                sb.Append("and convert(datetime,dPreDate, 20)" + "<= '" + json["eDate"].ToString() + "' ");
                //            }
                //            else if (obj.Name.ToString().Equals("cSOCode"))
                //            {
                //                sb.Append(" and d.cSOCode  like '%" +  json["cSOCode"].ToString() + "%' ");
                //            }
                //            else if (obj.Name.ToString().Equals("proCode"))
                //            {
                //                sb.Append(" and  d.cInvCode  like '%" + json["proCode"].ToString().Trim() + "%' ");
                //            }
                //            else if (obj.Name.ToString().Equals("proName"))
                //            {
                //                sb.Append(" and  p.cInvName  like '%" + json["proName"].ToString().Trim() + "%' ");
                //            }
                //            else if (obj.Name.ToString().Equals("customName"))
                //            {
                //                sb.Append(" and   m.cCusName  like '%" + json["customName"].ToString().Trim() + "%' ");
                //            }
                //            else
                //            {
                //                sb.Append(" and "+obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                //            }

                //        }
                //    }
                //}
                #endregion
                #endregion

                sb.Append(" order by d.cSOCode desc");
                #endregion

                var table = cuDb.getData(sb.ToString(), userLogin.UserInfo().baseCode);
                var list = cmd.TableToDictionary(table);

                #region 统计创建的计划数
                table = new DataTable();
                foreach (var s in list)
                {
                    // hasPlan 判断要货单是否创建计划
                    sb.Clear();
                    sb.Append(" select * from V_ProductionPlan_products where isdel = 0 and isosid = " + s["isosid"]);
                    table = cmd.GetDataTable(sb.ToString());
                    if (table.Rows.Count > 0)
                    {
                        s["hasPlan"] = "1";//已创建计划
                        #region 创建销售计划数
                        var rows = table.Select("plType='P-Sale'");
                        double num = 0;
                        if (rows.Length > 0)
                        {
                            foreach (DataRow dr in rows)
                            {
                                num = num + double.Parse(dr["number"].ToString());
                            }

                        }
                        s["sNum"] = num.ToString();
                        #endregion
                        #region 创建包装计划数
                        rows = table.Select("plType='P-Pack'");
                        num = 0;
                        if (rows.Length > 0)
                        {
                            foreach (DataRow dr in rows)
                            {
                                num = num + double.Parse(dr["number"].ToString());
                            }
                        }
                        s["pNum"] = num.ToString();
                        #endregion
                    }
                    else
                    {
                        s["hasPlan"] = "0";
                    }
                }
                #endregion

                # region 是否创建要货单 已注释

                //for (int i = 0; i < list.Count; i++)
                //{
                //    #region 是否创建要货单
                //    sb.Clear();
                //    sb.Append("select top 1 orderCode from pi_proAsk_info  ");
                //    sb.Append("where isdel =0 and orderCode='" + list[i]["orderCode"] + "' and proCode='" + list[i]["proCode"] + "'");
                //    sb.Append(" and rowNO='" + list[i]["rowNO"] + "' and cu_yanse='" + list[i]["cu_yanse"] + "' and cu_shangbiao='" + list[i]["cu_shangbiao"] + "'");
                //    list[i]["saleNum"] = list[i]["number"];
                //    var qTable = cmd.GetDataTable(sb.ToString());
                //    if (qTable.Rows.Count > 0)
                //    {
                //        list[i]["isUsed"] = "1";
                //    }
                //    else
                //    {
                //        list[i]["isUsed"] = "0";
                //    }
                //    #endregion
                //}
                #endregion

                //#region  获取已创建计划数
                //this.getPlanNum(json["plType"].ToString(), ref list);
                //#endregion
                rsl.Data = list;
                rsl.Result = true;
                return rsl;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return null;
        }
        /// <summary>
        /// 获取U8销售数据
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="saleId"></param>
        /// <param name="saleCode"></param>
        /// <returns></returns>
        public ReturnResult getNewSalesInfo(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            CuDbHelper cuDb = new CuDbHelper();
            try
            {


                StringBuilder sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                string orType = "";
                sb.Append("select parValue from sys_parameters_info where ");
                if (json["dTypes"].ToString() == "cm")
                {
                    sb.Append("parCode='cmSale'");
                }
                else
                {
                    sb.Append("parCode='jczdSale'");
                }
                var pTable = cmd.GetDataTable(sb.ToString());
                if (pTable.Rows.Count > 0)
                {
                    orType = pTable.Rows[0][0].ToString();
                }
                sb.Clear();
                sb.Append("select * from sys_CustomerBase_info where dbCode='" + userLogin.UserInfo().baseCode + "'");
                var bTable = cmd.GetDataTable(sb.ToString());
                string cuBaseName = string.Format("{0}.dbo.V_ZY_Bar_SaleInfo", bTable.Rows[0]["baseName"].ToString());

                sb.Clear();


                sb.Append(" cSOCode not in( select distinct relationOrder from pi_ProductionPlan_info where u8Order='1' ");
                sb.Append("and  proCode=" + cuBaseName + ".proCode" + ")");


                if (!string.IsNullOrWhiteSpace(orType))
                {
                    sb.Append("and cSTCode in (" + orType + ") ");
                }
                if (!string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                {
                    sb.Append("and convert(datetime,dDate, 20)" + " >='" + json["sDate"].ToString() + "' ");
                }
                if (!string.IsNullOrWhiteSpace(json["eDate"].ToString()))
                {//结束时间
                    sb.Append("and convert(datetime,dDate, 20)" + "<= '" + json["eDate"].ToString() + "' ");
                }
                //if (!string.IsNullOrWhiteSpace(json["spec"].ToString()))
                //{
                //    sb.Append(" and  spec  like '%" + json["spec"].ToString() + "%' ");
                //}
                //if (!string.IsNullOrWhiteSpace(json["cSOCode"].ToString()))
                //{
                //    sb.Append(" and  cSOCode  like '" + json["cSOCode"].ToString() + "' ");
                //}
                if (!string.IsNullOrWhiteSpace(json["customName"].ToString()))
                {
                    sb.Append(" and  customName  like '%" + json["customName"].ToString() + "%' ");
                }
                var datas = cmd.PageList<ViewU8SaleInfo>(cuBaseName, pageIndex, pageSize, sb.ToString(), "cSOCode DESC", ref pageCount);

                if (datas.Count > 0)
                {

                    sb.Clear();
                    sb.Append("select cInvCode,cUDValue from AA_InvFreeContrapose ");
                    var sxTable = cuDb.getData(sb.ToString(), userLogin.UserInfo().baseCode);
                    for (int i = 0; i < datas.Count; i++)
                    {
                        var dr = sxTable.Select("cInvCode='" + datas[i].proCode + "'");
                        string sx = "";
                        foreach (DataRow dRow in dr)
                        {
                            sx += dRow["cUDValue"].ToString() + ",";
                        }
                        datas[i].c_tssx = sx.TrimEnd(',');

                        //sb.Clear();
                        //sb.Append("select top 1 u8Order from pi_ProductionPlan_info where u8Order='1' ");
                        //sb.Append("and relationOrder='" + datas[i].cSOCode + "' and proCode='" + datas[i].proCode + "'");
                        //var qTable = cmd.GetDataTable(sb.ToString());
                        //if (qTable.Rows.Count > 0)
                        //{
                        //   datas[i].isUsed = "1";
                        //}
                        //else
                        //{
                        //    datas[i].isUsed = "0";
                        //}
                    }
                }


                rsl.Data = datas;
                rsl.Result = true;
                return rsl;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return null;
        }

        /// <summary>
        /// 印刷版是否在库
        /// </summary>
        /// <param name="ptCode"></param>
        /// <returns></returns>
        public ReturnResult CheckPlanBanGun(string ptCode)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                sb.Append("select bStatus from fun_BanGun_info where pCode in(");
                sb.Append("select c_bangun from pi_ProductionPlan_info where plCode in");
                sb.Append("(select plCode from pi_ProductionPlan_do_list where ");
                sb.Append(" ptCode='" + ptCode + "'))");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count < 1)
                {
                    rsl.Message = "没有版辊信息";
                }
                else
                {
                    if (table.Rows[0][0].ToString().ToLower() == "inhouse")
                    {
                        rsl.Result = true;
                    }
                    else
                    {
                        rsl.Message = "版辊当前不在库";
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取存货库存(U8)(按仓库)
        /// </summary>
        /// <param name="proCodes">关联存货编码集合</param>
        /// <returns></returns>
        public ReturnResult getProductStock(string datas)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                CuDbHelper helper = new CuDbHelper();
                if (string.IsNullOrWhiteSpace(datas))
                {
                    rsl.Message = "参数获取失败";
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(datas);

                sb.Clear();
                sb.Append("select p.cWhCode wareCode,p.cPosCode,p.cInvCode proCode,SUM(cast(iQuantity as decimal(10,2))) ");
                sb.Append("number,i.cInvName proName,po.cPosName,w.cWhName wareName,i.cInvStd spec,p.cFree1 color,");
                sb.Append("p.cFree3 shangbiao,'' usedNum from InvPositionSum  p inner join Inventory i on p.cInvCode=i.cInvCode ");
                sb.Append("inner join Warehouse w on w.cWhCode=p.cWhCode  ");
                sb.Append("inner join Position po on po.cPosCode=p.cPosCode where iQuantity>0  ");
                if (json["proCode"] != null && !string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    sb.Append("and i.cInvCode like '%" + json["proCode"].ToString() + "%'");
                }
                if (json["proName"] != null && !string.IsNullOrWhiteSpace(json["proName"].ToString()))
                {
                    sb.Append("and i.cInvName like '%" + json["proName"].ToString() + "%'");
                }
                if (json["wareName"] != null && !string.IsNullOrWhiteSpace(json["wareName"].ToString()))
                {
                    sb.Append("and w.cWhName like '%" + json["wareName"].ToString() + "%'");
                }

                sb.Append(" group by  p.cWhCode,p.cPosCode,p.cInvCode,i.cInvName,po.cPosName,w.cWhName,i.cInvStd ");
                sb.Append(" ,p.cFree1,p.cFree3  ");
                sb.Append(" order by p.cFree1 ");
                var poTable = helper.getData(sb.ToString(), userLogin.UserInfo().baseCode);

                rsl.Data = cmd.TableToDictionary(poTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取仓库存货库存(U8)
        /// </summary>
        /// <param name="proCodes">关联存货编码集合</param>
        /// <returns></returns>
        public ReturnResult getStock(string datas)
        {
            StringBuilder sb = new StringBuilder();
            rsl = new ReturnResult();
            try
            {
                CuDbHelper helper = new CuDbHelper();
                if (string.IsNullOrWhiteSpace(datas))
                {
                    rsl.Message = "参数获取失败";
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                if (string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    rsl.Message = "没有获取到相关存货信息";
                    return rsl;
                }

                #region 获取发货仓库 和货位
                sb.Append("select * from fun_CuWhMatch_info where cusCode = '" + json["cuCode"].ToString() + "'");
                var wTable = cmd.GetDataTable(sb.ToString());
                var wareHouse = "";
                var position = "";
                if (wTable.Rows.Count > 0)
                {
                    foreach (DataRow s in wTable.Rows)
                    {
                        wareHouse += "'" + s["wareCode"].ToString() + "',";
                        if (!string.IsNullOrWhiteSpace(s["positionCode"].ToString()))
                        {
                            position += "'" + s["positionCode"].ToString() + "',";
                        }
                    }
                }
                else
                {
                    wareHouse = "'012'";//备货库
                    position = "'t'";//图强货位
                }
                #endregion

                sb.Clear();
                //sb.Append("select w.cWhName,s.cWhCode,CONVERT(decimal(18), iQuantity) iQuantity,CONVERT(decimal(18), iQuantity) fhNum from CurrentStock s  ");
                //sb.Append("inner join Warehouse w on s.cWhCode=w.cWhCode  ");
                //sb.Append("where cInvCode like '%" + json["proCode"].ToString() + "%'  and cFree1 like '%" + json["color"].ToString() + "%' ");
                //sb.Append("and cFree3 like '%" + json["shangbiao"].ToString() + "%'  and s.cWhCode in (" + wareHouse.TrimEnd(',') + ") ");
                sb.Append("select w.cWhName,s.cWhCode,s.cPosCode,p.cPosName,CONVERT(decimal(18), iQuantity) iQuantity,CONVERT(decimal(18), iQuantity) fhNum  ");
                sb.Append("from InvPositionSum s inner join Warehouse w on s.cWhCode = w.cWhCode ");
                sb.Append("inner join Position p on p.cPosCode = s.cPosCode ");
                sb.Append("where cInvCode like '%" + json["proCode"].ToString() + "%'  and cFree1 like '%" + json["color"].ToString() + "%' ");
                sb.Append("and cFree3 like '%" + json["shangbiao"].ToString() + "%'  and s.cWhCode in (" + wareHouse.TrimEnd(',') + ") ");
                if (!string.IsNullOrWhiteSpace(position))
                {
                    sb.Append("and s.cPosCode in (" + position.TrimEnd(',') + ") ");
                }
                sb.Append("and CONVERT(decimal(18), iQuantity)> 0 ");

                var table = helper.getData(sb.ToString(), userLogin.UserInfo().baseCode);
                var list = cmd.TableToDictionary(table);//现存量

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 卷材制袋装计划状态
        /// </summary>
        /// <param name="planCode">计划单号</param>
        /// <param name="planCode">计划单号</param>
        /// <returns></returns>
        public ReturnResult ChanagePlanStatus(string plCode, string status, string msg, string userCode = "")
        {
            try
            {
                operList = new List<OperateModel>();
                DbProductionPlan plan = new DbProductionPlan();
                StringBuilder sb = new StringBuilder();
                plan.plCode = plCode;
                plan.status = status;
                oper = new OperateModel();
                oper.Data = plan;
                oper.Conditions = "plCode";
                oper.Types = OperateModel.OperateType.Edit;
                operList.Add(oper);
                DbApproveRecord r = new DbApproveRecord();
                r.businessCode = plCode;
                r.businessType = "Plan";
                r.createtime = getNow();
                if (string.IsNullOrWhiteSpace(userCode))
                {
                    userCode = userLogin.UserInfo().userCode;
                }
                r.createuser = userCode;
                r.memo = msg;
                r.result = status;
                oper = new OperateModel();
                oper.Data = r;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 设置工序调整价格信息
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <param name="value">修改值</param>
        /// <returns></returns>
        public ReturnResult SetGongXuPrice(string dataId, string value)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (!string.IsNullOrWhiteSpace(value))
                {
                    sb.Append("update pi_ProductionPlan_process set priceAdjust='" + value + "'");
                    sb.Append(" where id=" + dataId);
                    rsl = cmd.UpdateSql(sb.ToString());
                }
                else
                {
                    rsl.Message = "无需修改";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 计划占用库存数据
        /// </summary>
        /// <returns></returns>
        public ReturnResult PlanStockInfo(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select po.*,p.proName pProName,p.spec pSpec,p.status,p.statusName,p.status ");
                sb.Append("from V_ProductOccupy_info po inner join V_ProductPlan_info p on p.plCode=po.plCode ");
                sb.Append("and po.baseCode=p.baseCode ");
                sb.Append(" where po.isdel=0 and po.baseCode='" + userLogin.UserInfo().baseCode + "'");
                sb.Append(" and p.status in('pro-doing','do-finish') and po.barStatus !='bar-drop'");

                sb = CreateSelectCondition(sb, condition);
                sb.Append(" order by po.plCode desc");
                var table = cmd.GetDataTable(sb.ToString());
                List<string> rList = new List<string>();
                List<Dictionary<string, string>> dList = new List<Dictionary<string, string>>();
                foreach (DataRow r in table.Rows)
                {
                    string plCode = r["plCode"].ToString();
                    string wareHouse = r["houseName"].ToString();
                    string proCode = r["proCode"].ToString();
                    string spec = r["spec"].ToString();
                    string nStr = string.Format("{0}-{1}-{2}-{3}", plCode, proCode, spec, wareHouse);
                    if (!rList.Contains(nStr))
                    {
                        var dr = table.Select("plCode='" + plCode + "' and proCode='" + proCode + "' and spec='" + spec + "' and houseName='" + wareHouse + "'");
                        int bCount = dr.Length;
                        int nCount = 0;
                        foreach (DataRow drow in dr)
                        {
                            if (drow["barStatus"].ToString() == "need-out")
                            {
                                nCount++;
                            }
                        }
                        if (nCount > 0)
                        {
                            sb.Clear();
                            sb.Append("select createtime from pi_ProductionPlan_do where ptcode in(");
                            sb.Append("select ptCode from pi_ProductionPlan_do_list where plCode='" + plCode + "')");
                            var pgTable = cmd.GetDataTable(sb.ToString());
                            var dic = new Dictionary<string, string>();
                            dic["plCode"] = plCode;
                            if (pgTable.Rows.Count > 0)
                            {
                                dic["pgDate"] = pgTable.Rows[0][0].ToString();
                            }
                            else
                            {
                                dic["pgDate"] = "-";
                            }
                            dic["pProName"] = r["pProName"].ToString();
                            dic["pSpec"] = r["pSpec"].ToString();
                            dic["spec"] = spec;
                            dic["proCode"] = proCode;
                            dic["proName"] = r["proName"].ToString();
                            dic["spec"] = spec;
                            dic["wareHouse"] = wareHouse;
                            dic["zyCount"] = bCount.ToString();
                            dic["inCount"] = nCount.ToString();
                            dic["status"] = r["status"].ToString();
                            dic["pStatus"] = r["statusName"].ToString();
                            dList.Add(dic);
                        }
                        rList.Add(nStr);
                    }
                    if (dList.Count > 0)
                    {
                        rsl.Result = true;
                        rsl.Data = dList;
                    }
                    else
                    {
                        rsl.Message = "没有数据";
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 计划占用条码未出库数
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult PlanStockdetail(string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_BarCode_Info where barCode in(");
                sb.Append("select barCode from pi_ProductOccupy_info where plCode='" + plCode + "')");
                sb.Append(" and barStatus !='bar-drop' and status='Y' and baseCode='" + userLogin.UserInfo().baseCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 取消报工(卷材制袋)
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult DropPaiGong(string plCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                DbProductionPlan plan = new DbProductionPlan();
                plan.plCode = plCode;
                plan.status = "need-pg";
                oper = new OperateModel();
                oper.Data = plan;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "plCode";
                operList.Add(oper);
                DbProductionPlanDo pgdM = new DbProductionPlanDo();
                pgdM.plCode = plCode;
                pgdM.isDel = 1;
                pgdM.delDate = getNow();
                pgdM.delUser = userLogin.UserInfo().userCode;
                oper = new OperateModel();
                oper.Data = pgdM;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "plCode";
                operList.Add(oper);
                DbProductionPlanDoList pgdL = new DbProductionPlanDoList();
                pgdL.plCode = plCode;
                pgdL.isDel = 1;
                pgdL.delDate = getNow();
                pgdL.delUser = userLogin.UserInfo().userCode;
                oper = new OperateModel();
                oper.Data = pgdL;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "plCode";
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 码单
        /// </summary>
        /// <param name="info"></param>
        /// <param name="plCode"></param>
        /// <returns></returns>

        /// <summary>
        /// 生产计划新增存货
        /// </summary>
        /// <param name="datas">数据</param>
        /// <param name="plCode">计划编码</param>
        /// <param name="timeKey">时间戳</param>
        /// <returns></returns>
        //public ReturnResult AddTempPlanProduct(string datas,string plCode,string timeKey)
        //{
        //    rsl = new ReturnResult();
        //    try
        //    {
        //        var table = (DataTable)Tools.Cache.GetCache(timeKey);
        //        StringBuilder sb = new StringBuilder();
        //        #region 添加临时表列
        //        if (table == null || table.Columns.Count <1)
        //        {
        //            table = TempPlanProductTable();
        //        }
        //        #endregion
        //        var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);
        //        foreach (var obj in jsons)
        //        {
        //            var dr = table.Select("proCode='" + obj["proCode"].ToString() + "'");
        //            if (dr.Length < 1)//去重复
        //            {
        //                #region 添加
        //                var r = table.NewRow();
        //                r["plCode"] = plCode;
        //                r["proCode"] = obj["proCode"].ToString();
        //                r["proName"] = obj["proName"].ToString();
        //                r["spec"] = obj["spec"].ToString();
        //                if (obj.Property("number") == null)
        //                {
        //                    r["number"] = "1";
        //                }
        //                else
        //                {
        //                    r["number"] = obj["number"].ToString();
        //                }
        //                r["unit"] = obj["mUnit"].ToString();
        //                r["unitName"] = obj["mUnitName"].ToString();
        //                string inCount = "0", inNumber = "0";
        //                StockInfo(obj["proCode"].ToString(), ref inCount, ref inNumber);
        //                r["inNumber"] = inNumber;
        //                r["inCount"] = inCount;


        //                table.Rows.Add(r);
        //                #endregion
        //            }
        //        }
        //        Tools.Cache.SetCache(timeKey, table);
        //        rsl.Result = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        rsl.Message = ex.Message;
        //    }
        //    return rsl;
        //}

        /// <summary>
        /// 加载计划数据
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="timeKey">时间戳</param>
        /// <returns></returns>
        public ReturnResult loadTempPlanProduct(string plCode, string timeKey)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                var table = (DataTable)Tools.Cache.GetCache(timeKey);
                bool isInit = false;
                #region 创建临时表格
                if (table == null || table.Columns.Count < 1)
                {
                    isInit = true;
                    table = TempPlanProductTable();
                }
                #endregion
                if (isInit)
                {
                    if (!string.IsNullOrWhiteSpace(plCode))
                    {
                        sb.Append("select * from v_productionplan_products where plCode='" + plCode + "'");
                        sb.Append(" and isdel=0");
                        var ppTable = cmd.GetDataTable(sb.ToString());
                        bool isAdd = true;
                        #region 判断以存数据是否要进行显示
                        foreach (DataRow sr in table.Rows)
                        {
                            if (!string.IsNullOrWhiteSpace(sr["plCode"].ToString()))
                            {
                                isAdd = false;
                            }
                        }
                        if (isAdd)
                        {
                            foreach (DataRow row in ppTable.Rows)
                            {
                                var r = table.NewRow();
                                r["plCode"] = plCode;
                                r["proCode"] = row["proCode"].ToString();
                                r["proName"] = row["proName"].ToString();
                                r["spec"] = row["spec"].ToString();
                                r["number"] = row["number"].ToString();
                                r["unit"] = row["unit"].ToString();
                                r["unitName"] = row["unitName"].ToString();
                                string inCount = "0", inNumber = "0";
                                StockInfo(row["proCode"].ToString(), ref inCount, ref inNumber);
                                r["inCount"] = inCount;
                                r["inNumber"] = inNumber;
                                table.Rows.Add(r);
                            }
                        }
                        #endregion
                    }
                }
                Tools.Cache.SetCache(timeKey, table);
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 库存合计
        /// </summary>
        /// <param name="proCode"></param>
        /// <param name="inCount"></param>
        /// <param name="inNumber"></param>
        /// <param name="zyCount"></param>
        /// <param name="zyNumber"></param>
        private void StockInfo(string proCode, ref string inCount, ref string inNumber)
        {
            StringBuilder sb = new StringBuilder();
            #region 库存合计
            sb.Append("select barCode,number from V_BarCode_Info where barStatus='need-out' and");
            sb.Append(" proCode='" + proCode + "' and baseCode='" + userLogin.UserInfo().baseCode + "'");
            var barTable = cmd.GetDataTable(sb.ToString());
            double totalNum = 0;
            foreach (DataRow br in barTable.Rows)
            {
                totalNum += int.Parse(br["number"].ToString());
            }
            inNumber = totalNum.ToString();
            inCount = barTable.Rows.Count.ToString();
            #endregion

        }

        /// <summary>
        /// 生产计划存货临时表
        /// </summary>
        /// <returns></returns>
        private DataTable TempPlanProductTable()
        {
            var table = new DataTable();
            table.Columns.Add("plCode");
            table.Columns.Add("proCode");
            table.Columns.Add("proName");
            table.Columns.Add("spec");
            table.Columns.Add("number");
            table.Columns.Add("unit");
            table.Columns.Add("unitName");
            table.Columns.Add("inCount");//在库件数
            table.Columns.Add("inNumber");//在库件数
            return table;
        }

        /// <summary>
        /// U8存货现存量
        /// </summary>
        /// <param name="proCode">存货编码</param>
        /// <returns></returns>
        public ReturnResult U8_ProductStock(string condition)
        {
            rsl = new ReturnResult();
            CuDbHelper cuHelper = new CuDbHelper();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                string baseCode = userLogin.UserInfo().baseCode;
                StringBuilder sb = new StringBuilder();
                sb.Append("select s.cInvCode proCode,s.iQuantity number,s.cWhCode wareCode,p.cInvName proName,");
                sb.Append("p.cInvStd spec,w.cWhName wareName  from CurrentStock s");
                sb.Append(" inner join  Inventory p on s.cInvCode=p.cInvCode");
                sb.Append(" inner join Warehouse w on w.cWhCode=s.cWhCode where iQuantity>0 ");
                if (!string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    sb.Append(" and s.cInvCode='" + json["proCode"].ToString() + "'");
                }
                var table = cuHelper.getData(sb.ToString(), baseCode);
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取erp系统全部有效发货单数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        private DataTable ERPSendOrder(string baseCode)
        {
            CuDbHelper cuDb = new CuDbHelper();
            string tCodes = "";
            StringBuilder sb = new StringBuilder();
            sb.Clear();
            sb.Append("select * from sys_parameters_info where parCode='fyType' and isdel=0 ");
            sb.Append("and enable='open'");
            var parTable = cmd.GetDataTable(sb.ToString());
            if (parTable.Rows.Count > 0 && parTable.Rows[0]["parValue"] != null)
            {
                var cArr = parTable.Rows[0]["parValue"].ToString().Replace("，", ",").Split(',');
                foreach (string s in cArr)
                {
                    if (!string.IsNullOrWhiteSpace(s))
                    {
                        tCodes += string.Format("'{0}',", s);
                    }
                }
            }
            sb.Clear();
            sb.Append("select s.cInvCode proCode,s.cInvName proName,s.cWhCode,s.iQuantity number,fOutQuantity outNumber,");
            sb.Append("m.cDLCode orderCode,cVouchType,m.dDate,m.cCusCode cuCode,m.cCusName cuName,s.irowno rowNO  ");
            sb.Append("from DispatchLists s inner join DispatchList m on m.DLID=s.DLID  ");
            sb.Append(" where m.dverifydate is not null and m.dverifydate !='' and (s.iQuantity>s.fOutQuantity or s.fOutQuantity is null)");
            sb.Append(" and convert(date,dDate, 20)" + " >='" + getNowDate(-1) + "' ");
            if (!string.IsNullOrWhiteSpace(tCodes))
            {
                sb.Append(" and s.cInvCode not in(select cinvCode from inventory where cInvCCode in(" + tCodes.TrimEnd(',') + "))");
            }
            var table = cuDb.getData(sb.ToString(), baseCode);
            return table;

        }
        /// <summary>
        /// 获取用户关联发货单
        /// </summary>
        /// <returns></returns>
        public ReturnResult UserOutOrders(string userCode = "", string baseCode = "")
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    baseCode = userLogin.UserInfo().baseCode;
                }
                var orTable = this.ERPSendOrder(baseCode);
                sb.Append("select cuCode,userCode from V_CuManager where isdel=0");
                if (!string.IsNullOrWhiteSpace(userCode))
                {
                    sb.Append(" and userCode='" + userCode + "'");
                }
                var ucTable = cmd.GetDataTable(sb.ToString());//获取客户人员配置对应数据表
                List<Dictionary<string, object>> dList = new List<Dictionary<string, object>>();
                Dictionary<string, object> d;
                List<string> reList = new List<string>();
                foreach (DataRow r in ucTable.Rows)
                {
                    var dr = orTable.Select("cuCode='" + r["cuCode"].ToString() + "'");
                    if (dr.Length > 0)
                    {
                        var tem = dr.CopyToDataTable();
                        foreach (DataRow trow in tem.Rows)
                        {
                            string orCode = trow["orderCode"].ToString();
                            var tdrs = tem.Select("orderCode='" + orCode + "'");
                            if (!reList.Contains(orCode))
                            {//以发货单号为唯一标识
                                d = new Dictionary<string, object>();
                                d["userCode"] = r["userCode"].ToString();
                                d["orderCode"] = orCode;
                                d["cuName"] = tdrs[0]["cuName"].ToString();
                                List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                                foreach (var t_dr in tdrs)
                                {
                                    var cd = new Dictionary<string, object>();
                                    cd["proName"] = t_dr["proName"];
                                    cd["number"] = Math.Round(double.Parse(t_dr["number"].ToString()), 2);
                                    cList.Add(cd);
                                }
                                d["list"] = cList;
                                dList.Add(d);
                                reList.Add(orCode);
                            }
                        }
                    }
                }
                if (dList.Count > 0)
                {
                    rsl.Data = dList;
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没有数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 发货单消息发送消息
        /// </summary>
        /// <returns></returns>
        public ReturnResult SendOutOrderMsg(string baseCode = "")
        {
            rsl = new ReturnResult();
            try
            {
                SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                }

                var r = this.UserOutOrders("", baseCode);
                if (r.Result)
                {
                    var list = (List<Dictionary<string, object>>)r.Data;
                    SysFrameWork.DingHelper ding = new SysFrameWork.DingHelper();
                    StringBuilder sb = new StringBuilder();
                    string tCode = "SOM";
                    foreach (var d in list)
                    {
                        var key = d["orderCode"].ToString() + d["userCode"];
                        sb.Clear();
                        sb.Append("select id from sys_SendMsg_info where businessType='" + tCode + "'");
                        sb.Append(" and isResult='1' and businessId='" + key + "'");
                        var qtable = cmd.GetDataTable(sb.ToString());
                        if (qtable.Rows.Count < 1)
                        {
                            sb.Clear();
                            sb.Append("客户：" + d["cuName"]);
                            sb.Append("\n");
                            sb.Append("单号：" + d["orderCode"]);
                            sb.Append("\n");
                            string msg = "";
                            var datas = (List<Dictionary<string, object>>)d["list"];
                            foreach (var cd in datas)
                            {
                                msg += string.Format("{0}({1})", cd["proName"], cd["number"]);
                            }
                            sb.Append(msg); sb.Append("\n"); sb.Append("请及时处理，谢谢！");
                            ding.sendDingMsg("SOM", key, d["userCode"].ToString(), sb.ToString(), "admin");
                        }

                    }

                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取计划工序信息
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult getProcessPG(string ids, string gxCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" select p.id,plCode,proCode,saleNum,p.number,proName ,pLevel,gxCode,");
                sb.Append("'' isUrgent,isnull(sum(convert(decimal(18, 2), pg.number)), 0) ypgNum ");
                sb.Append("from V_ProductionPlan_products p ");
                sb.Append("left join pi_PlanPaiGong_info pg on pg.isDel=0 and pg.ppId = p.id and gxCode='" + gxCode + "' ");
                sb.Append("where p.id in (" + ids + ") ");
                sb.Append("group by p.id,plCode,proCode,saleNum,p.number,proName,gxCode ,pLevel ");
                sb.Append("order by id desc ");
                var table = cmd.GetDataTable(sb.ToString());
                var list = cmd.TableToDictionary(table);

                foreach (var s in list)
                {
                    //派工数量默认为计划数量-已派工数量
                    s["pgNum"] = (Convert.ToDecimal(s["number"].ToString()) - Convert.ToDecimal(s["ypgNum"].ToString())).ToString();

                    if (s["pLevel"].ToString().Equals("100"))
                        s["isUrgent"] = "0";
                    else
                        s["isUrgent"] = "1";
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// 获取计划工序存货的库存
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public DataTable getProcessStock(string ids)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select s.cInvCode proCode,s.cInvName proName,s.cWhCode,s.iQuantity number,m.cDLCode orderCode,");
            sb.Append("m.cCusCode cuCode,m.cCusName cuName,s.irowno rowNO from DispatchLists s ");
            sb.Append("inner join DispatchList m on m.DLID=s.DLID ");
            // sb.Append(" where m.dverifydate is not null and m.dverifydate !=''");
            var table = cmd.GetDataTable(sb.ToString());
            return table;

        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="organizationId"></param>
        /// <returns></returns>
        public ReturnResult ImportBhPlan(HttpPostedFileBase file, string type = null)
        {
            rsl = new ReturnResult();
            var temI = "";
            #region
            try
            {
                //HttpPostedFile file = HttpContext.Current.Request.Files[0];
                string FileName;
                string savePath;
                if (file == null || file.ContentLength <= 0)
                {
                    rsl.Message = "文件为空!";
                }
                else
                {
                    #region 将上传的文件存到固定地址
                    string filename = Path.GetFileName(file.FileName);
                    int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
                    string fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名
                    string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
                    int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
                    string FileType = ".xls,.xlsx";//定义上传文件的类型字符串

                    FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + NoFileName + fileEx;
                    if (!FileType.Contains(fileEx))
                    {
                        rsl.Message = ("文件类型不对，只能导入xls和xlsx格式的文件！");
                        return rsl;
                    }
                    if (filesize >= Maxsize)
                    {
                        rsl.Message = ("上传文件超过4M，不能上传！");
                        return rsl;
                    }

                    string path = HostingEnvironment.MapPath("~/files/");
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);//根据路径创建指定文件
                    savePath = Path.Combine(path, FileName);
                    file.SaveAs(savePath);
                    #endregion
                    //DataTable table = GetExcelData(savePath).Tables[0];   //读取excel内容
                    //DataTable table = ReadExcelToDataSet(savePath).Tables[0];   //读取excel内容
                    DataTable table = method.ReadExcelToDataTable(savePath);   //读取excel内容
                    
                    string plCode = "", proCode = "", color = "", gyCode = "", shangbiao = "";
                    operList = new List<OperateModel>();

                    #region   对excel表内信息进行 工序编码重复验证 

                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        temI = i.ToString();
                        #region 非空验证等
                        if (string.IsNullOrWhiteSpace(table.Rows[i]["序号"].ToString()))
                        {
                            break;
                        }
                        if (string.IsNullOrWhiteSpace(table.Rows[i]["货号"].ToString()))
                        {
                            rsl.Message = ("第" + table.Rows[i]["序号"].ToString() + "行货号不能为空");
                            return rsl;
                        }
                        if (string.IsNullOrWhiteSpace(type))
                        {
                            if (string.IsNullOrWhiteSpace(table.Rows[i]["颜色"].ToString()))
                            {
                                rsl.Message = ("第" + table.Rows[i]["序号"].ToString() + "行颜色不能为空");
                                return rsl;
                            }
                            if (string.IsNullOrWhiteSpace(table.Rows[i]["商标"].ToString()))
                            {
                                rsl.Message = ("第" + table.Rows[i]["序号"].ToString() + "行商标不能为空");
                                return rsl;
                            }
                        }

                        if (string.IsNullOrWhiteSpace(table.Rows[i]["数量"].ToString()))//|| Convert.ToDecimal(table.Rows[i]["数量"].ToString()) < 0
                        {
                            rsl.Message = ("第" + table.Rows[i]["序号"].ToString() + "行数量不能为空");
                            return rsl;
                        }
                        if (string.IsNullOrWhiteSpace(table.Rows[i]["工艺编码"].ToString()))
                        {
                            rsl.Message = ("第" + table.Rows[i]["序号"].ToString() + "行工艺编码不能为空");
                            return rsl;
                        }
                        #endregion

                        #region 计划编码重复验证
                        DataRow[] dRows = table.Select("生产计划号='" + table.Rows[i][1].ToString() + "' and 生产计划号<>''");
                        if (dRows.Length > 1)
                        {
                            rsl.Message = ("当前EXCEl表中存在相同的生产计划号：") + table.Rows[i][1].ToString();
                            return rsl;
                        }
                        #endregion
                    }
                    temI = "";
                    #endregion

                    DbProductionPlan plan;
                    DbProductionPlanPro pp;
                    DbPlanGongXu gx;
                    #region  对excel表内信息进行货号、颜色、工艺编码是否存在的验证 是否与已有计划编码重复验证  和添加操作
                    foreach (DataRow dr in table.Rows)
                    {
                        if (string.IsNullOrWhiteSpace(dr["序号"].ToString()))
                        {
                            break;
                        }
                        string sql = "";
                        var sqlTable = new DataTable();
                        #region 判断计划编码是否重复  如果没有计划号，则生成一个
                        if (string.IsNullOrWhiteSpace(dr["生产计划号"].ToString()))
                        {
                            string codeLength = Tools.ConfigReader.Reader["CodeLength"];
                            plCode = CreatePlanCodeInfo("PO", "生产计划编码", int.Parse(codeLength));
                        }
                        else
                        {
                            sql = "select * from pi_ProductionPlan_info where plCode='" + dr["生产计划号"].ToString() + "' and isdel=0 ";
                            sqlTable = cmd.GetDataTable(sql.ToString());
                            if (sqlTable.Rows.Count > 0)
                            {
                                rsl.Message = "当前系统中已存在此生产计划号：" + dr["生产计划号"].ToString();
                                return rsl;
                            }
                            else
                            {
                                plCode = dr["生产计划号"].ToString();
                            }
                        }

                        #endregion
                        #region 判断是否有存货（货号）
                        sql = "select proCode from fun_Inventory_Info where proCode='" + dr["货号"].ToString() + "' " +
                            "and baseCode='" + userLogin.UserInfo().baseCode + "' and isDel=0 ";
                        sqlTable = cmd.GetDataTable(sql.ToString());
                        if (sqlTable.Rows.Count > 0)
                        {
                            proCode = sqlTable.Rows[0]["proCode"].ToString();
                        }
                        else
                        {
                            rsl.Message = "当前系统中不存在此货号：" + dr["货号"].ToString();
                            return rsl;
                        }
                        #endregion
                        if (string.IsNullOrWhiteSpace(type))
                        {
                            #region 判断存货颜色是否正确
                            sql = "select cCode from fun_CommonData_Info where specFile='" + userLogin.UserInfo().baseCode + "' " +
                                "and isDel=0 and cType='proColor' and  parentCode= '" + dr["货号"].ToString() + "' " +
                                "and cCode='" + dr["颜色"].ToString() + "'";
                            sqlTable = cmd.GetDataTable(sql.ToString());
                            if (sqlTable.Rows.Count > 0)
                            {
                                color = sqlTable.Rows[0]["cCode"].ToString();
                            }
                            else
                            {
                                //存货没有自由项的话，则验证全部自由项有没有这个颜色
                                sql = "select cCode from fun_CommonData_Info where specFile='" + userLogin.UserInfo().baseCode + "' " +
                                    " and isDel=0  and cType='proColor' and parentCode is null and cCode='" + dr["颜色"].ToString() + "'";
                                sqlTable = cmd.GetDataTable(sql.ToString());
                                if (sqlTable.Rows.Count > 0)
                                {
                                    color = sqlTable.Rows[0]["cCode"].ToString();
                                }
                                else
                                {
                                    rsl.Message = "第" + dr["序号"].ToString() + "行，颜色：" + dr["颜色"].ToString() + "不属于存货：" + dr["货号"].ToString();
                                    return rsl;
                                }
                            }
                            #endregion
                            #region 判断存货商标是否正确
                            sql = "select cCode from fun_CommonData_Info where specFile='" + userLogin.UserInfo().baseCode + "' " +
                                "and isDel=0 and cType='proBrand' and  parentCode= '" + dr["货号"].ToString() + "' " +
                                "and cCode='" + dr["商标"].ToString() + "'";
                            sqlTable = cmd.GetDataTable(sql.ToString());
                            if (sqlTable.Rows.Count > 0)
                            {
                                shangbiao = sqlTable.Rows[0]["cCode"].ToString();
                            }
                            else
                            {
                                //存货没有自由项的话，则验证全部自由项有没有这个商标
                                sql = "select cCode from fun_CommonData_Info where specFile='" + userLogin.UserInfo().baseCode + "' " +
                                    " and isDel=0  and cType='proBrand' and parentCode is null and cCode='" + dr["商标"].ToString() + "'";
                                sqlTable = cmd.GetDataTable(sql.ToString());
                                if (sqlTable.Rows.Count > 0)
                                {
                                    shangbiao = sqlTable.Rows[0]["cCode"].ToString();
                                }
                                else
                                {
                                    rsl.Message = "第" + dr["序号"].ToString() + "行，商标：" + dr["商标"].ToString() + "不属于存货：" + dr["货号"].ToString();
                                    return rsl;
                                }
                            }
                            #endregion
                        }

                        #region 判断工艺编码是否存在
                        sql = "select p.gxCode,pr.gxCode parentCode, c.orderNum from fun_products_gx p inner join fun_GxPrice_info pr" +
                        " on p.gxCode=pr.cgxCode and pr.isdel=0 inner join fun_CommonData_Info c on pr.gxCode = c.cCode and c.cType = 'Gx'" +
                        " where gyCode='" + dr["工艺编码"].ToString() + "' order by c.orderNum ";
                        sqlTable = cmd.GetDataTable(sql.ToString());
                        if (sqlTable.Rows.Count > 0)
                        {
                            gyCode = sqlTable.Rows[0]["gxCode"].ToString();
                        }
                        else
                        {
                            rsl.Message = "当前系统中不存在此工艺编码：" + dr["工艺编码"].ToString();
                            return rsl;
                        }
                        #endregion

                        #region  向计划表、子表、工序表添加数据
                        plan = new DbProductionPlan();
                        pp = new DbProductionPlanPro();

                        #region 主表
                        plan.plCode = plCode;
                        if (string.IsNullOrWhiteSpace(type))
                        {
                            plan.plType = "P-BeiHuo";
                        }
                        else
                        {
                            plan.plType = "P-ZhiZao";
                        }
                        plan.relationOrder = "";
                        plan.number = dr["数量"].ToString();
                        plan.status = "ps-pg-set";
                        plan.createtime = getNow();
                        plan.createuser = userLogin.UserInfo().userCode;
                        plan.isdel = 0;
                        plan.needPack = 0;
                        plan.memo = dr["生产备注"].ToString();
                        plan.pLevel = "100";

                        plan.pStatus = "pass";

                        oper = new OperateModel();
                        oper.Types = OperateModel.OperateType.Add;
                        oper.Data = plan;
                        operList.Add(oper);
                        #endregion
                        #region 子表
                        pp.plCode = plCode;
                        pp.proCode = dr["货号"].ToString();
                        pp.number = dr["数量"].ToString();
                        pp.orderCode = "";
                        if (string.IsNullOrEmpty(dr["工艺编码"].ToString()))
                            pp.status = "ps-gy-set";
                        else
                            pp.status = "ps-pg-set";
                        //pp.payDate =getNow();
                        pp.rowNO = "1";
                        pp.isdel = 0;
                        pp.createtime = getNow();
                        pp.createuser = userLogin.UserInfo().userCode;
                        if (string.IsNullOrWhiteSpace(type))
                        {
                            pp.cu_yanse = dr["颜色"].ToString();
                            pp.cu_shangbiao = dr["商标"].ToString();
                        }
                        pp.cu_gy = dr["工艺编码"].ToString();
                        pp.memo = dr["生产备注"].ToString();
                        pp.prlCode = plCode + "-" + pp.rowNO;
                        oper = new OperateModel();
                        oper.Types = OperateModel.OperateType.Add;
                        oper.Data = pp;
                        operList.Add(oper);
                        #endregion
                        #region 工序

                        var fstGX = sqlTable.Rows[0]["parentCode"].ToString();//第一道工序
                        foreach (DataRow sdr in sqlTable.Rows)
                        {
                            gx = new DbPlanGongXu();
                            gx.plCode = plCode;
                            gx.proCode = dr["货号"].ToString();
                            gx.rowNo = "1";
                            gx.orderCode = "";
                            gx.gxCode = sdr["gxCode"].ToString();
                            gx.createtime = getNow();
                            gx.createuser = userLogin.UserInfo().userCode;
                            gx.isChild = 1;
                            gx.parentCode = sdr["parentCode"].ToString();
                            gx.status = "ps-dsc";
                            gx.gyCode = dr["工艺编码"].ToString();
                            if (sdr["parentCode"].ToString().Equals(fstGX))

                                gx.canBg = 1;
                            else
                                gx.canBg = 0;
                            oper = new OperateModel();
                            oper.Types = OperateModel.OperateType.Add;
                            oper.Data = gx;
                            operList.Add(oper);
                        }
                        #endregion

                        #endregion
                    }
                    #endregion
                    if (operList.Count < 1)
                    {
                        rsl.Message = "未获取到导入数据";
                        return rsl;
                    }
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        #region  向process中写入products的id  统计用
                        var sql = "select distinct p.id ,p.plCode,p.rowNO from pi_ProductionPlan_products p " +
                            "inner join pi_ProductionPlan_process pr on pr.plCode = p.plCode and pr.rowNo = p.rowNO " +
                            "where p.isdel = 0 and pr.ppId is null";
                        var ptable = cmd.GetDataTable(sql);
                        operList = new List<OperateModel>();
                        foreach (DataRow dr in ptable.Rows)
                        {
                            gx = new DbPlanGongXu();
                            gx.plCode = dr["plCode"].ToString();
                            gx.rowNo = dr["rowNo"].ToString();
                            gx.ppId = dr["id"].ToString();
                            oper = new OperateModel();
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "plCode,rowNo";
                            oper.Data = gx;
                            operList.Add(oper);
                        }
                        rsl = cmd.MoreUpdate(operList);

                        #endregion
                    }
                    else
                    {
                        return rsl;
                    }
                }//else end
            }
            catch (Exception ex)
            {
                rsl.Message = "第" + (temI + 1) + "行" + ex.Message;
                return rsl;
            }
            return rsl;
            #endregion

        }//function end

        ///// <summary>
        ///// 导入织造计划
        ///// </summary>
        ///// <param name="organizationId"></param>
        ///// <returns></returns>
        //public ReturnResult ImportZZPlan(HttpPostedFileBase file)
        //{
        //    rsl = new ReturnResult();
        //    var temI = "";
        //    #region
        //    try
        //    {
        //        //HttpPostedFile file = HttpContext.Current.Request.Files[0];
        //        string FileName;
        //        string savePath;
        //        if (file == null || file.ContentLength <= 0)
        //        {
        //            rsl.Message = "文件为空!";
        //        }
        //        else
        //        {
        //            #region 将上传的文件存到固定地址
        //            string filename = Path.GetFileName(file.FileName);
        //            int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
        //            string fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名
        //            string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
        //            int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
        //            string FileType = ".xls,.xlsx";//定义上传文件的类型字符串

        //            FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + NoFileName + fileEx;
        //            if (!FileType.Contains(fileEx))
        //            {
        //                rsl.Message = ("文件类型不对，只能导入xls和xlsx格式的文件！");
        //                return rsl;
        //            }
        //            if (filesize >= Maxsize)
        //            {
        //                rsl.Message = ("上传文件超过4M，不能上传！");
        //                return rsl;
        //            }

        //            string path = HostingEnvironment.MapPath("~/files/");
        //            if (!Directory.Exists(path))
        //                Directory.CreateDirectory(path);//根据路径创建指定文件
        //            savePath = Path.Combine(path, FileName);
        //            file.SaveAs(savePath);
        //            #endregion
        //            //DataTable table = GetExcelData(savePath).Tables[0];   //读取excel内容
        //            //DataTable table = ReadExcelToDataSet(savePath).Tables[0];   //读取excel内容
        //            DataTable table = method.ReadExcelToDataTable(savePath);   //读取excel内容

        //            string plCode = "", proCode = "", color = "", gyCode = "", shangbiao = "";
        //            operList = new List<OperateModel>();

        //            #region   对excel表内信息进行 工序编码重复验证 

        //            for (int i = 0; i < table.Rows.Count; i++)
        //            {
        //                temI = i.ToString();
        //                #region 非空验证等
        //                if (string.IsNullOrWhiteSpace(table.Rows[i]["序号"].ToString()))
        //                {
        //                    break;
        //                }
        //                if (string.IsNullOrWhiteSpace(table.Rows[i]["货号"].ToString()))
        //                {
        //                    rsl.Message = ("第" + table.Rows[i]["序号"].ToString() + "行货号不能为空");
        //                    return rsl;
        //                }
        //                if (string.IsNullOrWhiteSpace(table.Rows[i]["数量"].ToString()))//|| Convert.ToDecimal(table.Rows[i]["数量"].ToString()) < 0
        //                {
        //                    rsl.Message = ("第" + table.Rows[i]["序号"].ToString() + "行数量不能为空");
        //                    return rsl;
        //                }
        //                if (string.IsNullOrWhiteSpace(table.Rows[i]["工艺编码"].ToString()))
        //                {
        //                    rsl.Message = ("第" + table.Rows[i]["序号"].ToString() + "行工艺编码不能为空");
        //                    return rsl;
        //                }
        //                #endregion

        //                #region 计划编码重复验证
        //                DataRow[] dRows = table.Select("生产计划号='" + table.Rows[i][1].ToString() + "' and 生产计划号<>''");
        //                if (dRows.Length > 1)
        //                {
        //                    rsl.Message = ("当前EXCEl表中存在相同的生产计划号：") + table.Rows[i][1].ToString();
        //                    return rsl;
        //                }
        //                #endregion
        //            }
        //            temI = "";
        //            #endregion

        //            DbProductionPlan plan;
        //            DbProductionPlanPro pp;
        //            DbPlanGongXu gx;
        //            #region  对excel表内信息进行货号、工艺编码是否存在的验证 是否与已有计划编码重复验证  和添加操作
        //            foreach (DataRow dr in table.Rows)
        //            {
        //                if (string.IsNullOrWhiteSpace(dr["序号"].ToString()))
        //                {
        //                    break;
        //                }
        //                string sql = "";
        //                var sqlTable = new DataTable();
        //                #region 判断计划编码是否重复  如果没有计划号，则生成一个
        //                if (string.IsNullOrWhiteSpace(dr["生产计划号"].ToString()))
        //                {
        //                    string codeLength = Tools.ConfigReader.Reader["CodeLength"];
        //                    plCode = CreatePlanCodeInfo("PO", "生产计划编码", int.Parse(codeLength));
        //                }
        //                else
        //                {
        //                    sql = "select * from pi_ProductionPlan_info where plCode='" + dr["生产计划号"].ToString() + "' and isdel=0 ";
        //                    sqlTable = cmd.GetDataTable(sql.ToString());
        //                    if (sqlTable.Rows.Count > 0)
        //                    {
        //                        rsl.Message = "当前系统中已存在此生产计划号：" + dr["生产计划号"].ToString();
        //                        return rsl;
        //                    }
        //                    else
        //                    {
        //                        plCode = dr["生产计划号"].ToString();
        //                    }
        //                }

        //                #endregion
        //                #region 判断是否有存货（货号）
        //                sql = "select proCode from fun_Inventory_Info where proCode='" + dr["货号"].ToString() + "' " +
        //                    "and baseCode='" + userLogin.UserInfo().baseCode + "' and isDel=0 ";
        //                sqlTable = cmd.GetDataTable(sql.ToString());
        //                if (sqlTable.Rows.Count > 0)
        //                {
        //                    proCode = sqlTable.Rows[0]["proCode"].ToString();
        //                }
        //                else
        //                {
        //                    rsl.Message = "当前系统中不存在此货号：" + dr["货号"].ToString();
        //                    return rsl;
        //                }
        //                #endregion
        //                # region 判断存货颜色是否正确
        //                sql = "select cCode from fun_CommonData_Info where specFile='" + userLogin.UserInfo().baseCode + "' " +
        //                    "and isDel=0 and cType='proColor' and  parentCode= '" + dr["货号"].ToString() + "' " +
        //                    "and cCode='" + dr["颜色"].ToString() + "'";
        //                sqlTable = cmd.GetDataTable(sql.ToString());
        //                if (sqlTable.Rows.Count > 0)
        //                {
        //                    color = sqlTable.Rows[0]["cCode"].ToString();
        //                }
        //                else
        //                {
        //                    //存货没有自由项的话，则验证全部自由项有没有这个颜色
        //                    sql = "select cCode from fun_CommonData_Info where specFile='" + userLogin.UserInfo().baseCode + "' " +
        //                        " and isDel=0  and cType='proColor' and parentCode is null and cCode='" + dr["颜色"].ToString() + "'";
        //                    sqlTable = cmd.GetDataTable(sql.ToString());
        //                    if (sqlTable.Rows.Count > 0)
        //                    {
        //                        color = sqlTable.Rows[0]["cCode"].ToString();
        //                    }
        //                    else
        //                    {
        //                        rsl.Message = "第" + dr["序号"].ToString() + "行，颜色：" + dr["颜色"].ToString() + "不属于存货：" + dr["货号"].ToString();
        //                        return rsl;
        //                    }
        //                }
        //                #endregion
        //                # region 判断存货商标是否正确
        //                sql = "select cCode from fun_CommonData_Info where specFile='" + userLogin.UserInfo().baseCode + "' " +
        //                    "and isDel=0 and cType='proBrand' and  parentCode= '" + dr["货号"].ToString() + "' " +
        //                    "and cCode='" + dr["商标"].ToString() + "'";
        //                sqlTable = cmd.GetDataTable(sql.ToString());
        //                if (sqlTable.Rows.Count > 0)
        //                {
        //                    shangbiao = sqlTable.Rows[0]["cCode"].ToString();
        //                }
        //                else
        //                {
        //                    //存货没有自由项的话，则验证全部自由项有没有这个商标
        //                    sql = "select cCode from fun_CommonData_Info where specFile='" + userLogin.UserInfo().baseCode + "' " +
        //                        " and isDel=0  and cType='proBrand' and parentCode is null and cCode='" + dr["商标"].ToString() + "'";
        //                    sqlTable = cmd.GetDataTable(sql.ToString());
        //                    if (sqlTable.Rows.Count > 0)
        //                    {
        //                        shangbiao = sqlTable.Rows[0]["cCode"].ToString();
        //                    }
        //                    else
        //                    {
        //                        rsl.Message = "第" + dr["序号"].ToString() + "行，商标：" + dr["商标"].ToString() + "不属于存货：" + dr["货号"].ToString();
        //                        return rsl;
        //                    }
        //                }
        //                #endregion
        //                #region 判断工艺编码是否存在
        //                sql = "select p.gxCode,pr.gxCode parentCode, c.orderNum from fun_products_gx p inner join fun_GxPrice_info pr" +
        //                " on p.gxCode=pr.cgxCode and pr.isdel=0 inner join fun_CommonData_Info c on pr.gxCode = c.cCode and c.cType = 'Gx'" +
        //                " where gyCode='" + dr["工艺编码"].ToString() + "' order by c.orderNum ";
        //                sqlTable = cmd.GetDataTable(sql.ToString());
        //                if (sqlTable.Rows.Count > 0)
        //                {
        //                    gyCode = sqlTable.Rows[0]["gxCode"].ToString();
        //                }
        //                else
        //                {
        //                    rsl.Message = "当前系统中不存在此工艺编码：" + dr["工艺编码"].ToString();
        //                    return rsl;
        //                }
        //                #endregion

        //                #region  向计划表、子表、工序表添加数据
        //                plan = new DbProductionPlan();
        //                pp = new DbProductionPlanPro();

        //                #region 主表
        //                plan.plCode = plCode;
        //                plan.plType = "P-BeiHuo";
        //                plan.relationOrder = "";
        //                plan.number = dr["数量"].ToString();
        //                plan.status = "ps-pg-set";
        //                plan.createtime = getNow();
        //                plan.createuser = userLogin.UserInfo().userCode;
        //                plan.isdel = 0;
        //                plan.needPack = 0;
        //                plan.memo = dr["生产备注"].ToString();
        //                plan.pLevel = "100";

        //                plan.pStatus = "pass";

        //                oper = new OperateModel();
        //                oper.Types = OperateModel.OperateType.Add;
        //                oper.Data = plan;
        //                operList.Add(oper);
        //                #endregion
        //                #region 子表
        //                pp.plCode = plCode;
        //                pp.proCode = dr["货号"].ToString();
        //                pp.number = dr["数量"].ToString();
        //                pp.orderCode = "";
        //                if (string.IsNullOrEmpty(dr[6].ToString()))
        //                    pp.status = "ps-gy-set";
        //                else
        //                    pp.status = "ps-pg-set";
        //                //pp.payDate =getNow();
        //                pp.rowNO = "1";
        //                pp.isdel = 0;
        //                pp.createtime = getNow();
        //                pp.createuser = userLogin.UserInfo().userCode;
        //                pp.cu_yanse = dr["颜色"].ToString();
        //                pp.cu_shangbiao = dr["商标"].ToString();
        //                pp.cu_gy = dr["工艺编码"].ToString();
        //                pp.memo = dr["生产备注"].ToString();
        //                pp.prlCode = plCode + "-" + pp.rowNO;
        //                oper = new OperateModel();
        //                oper.Types = OperateModel.OperateType.Add;
        //                oper.Data = pp;
        //                operList.Add(oper);
        //                #endregion
        //                #region 工序

        //                var fstGX = sqlTable.Rows[0]["parentCode"].ToString();//第一道工序
        //                foreach (DataRow sdr in sqlTable.Rows)
        //                {
        //                    gx = new DbPlanGongXu();
        //                    gx.plCode = plCode;
        //                    gx.proCode = dr["货号"].ToString();
        //                    gx.rowNo = "1";
        //                    gx.orderCode = "";
        //                    gx.gxCode = sdr["gxCode"].ToString();
        //                    gx.createtime = getNow();
        //                    gx.createuser = userLogin.UserInfo().userCode;
        //                    gx.isChild = 1;
        //                    gx.parentCode = sdr["parentCode"].ToString();
        //                    gx.status = "ps-dsc";
        //                    gx.gyCode = dr["工艺编码"].ToString();
        //                    if (sdr["parentCode"].ToString().Equals(fstGX))

        //                        gx.canBg = 1;
        //                    else
        //                        gx.canBg = 0;
        //                    oper = new OperateModel();
        //                    oper.Types = OperateModel.OperateType.Add;
        //                    oper.Data = gx;
        //                    operList.Add(oper);
        //                }
        //                #endregion

        //                #endregion
        //            }
        //            #endregion
        //            if (operList.Count < 1)
        //            {
        //                rsl.Message = "未获取到导入数据";
        //                return rsl;
        //            }
        //            rsl = cmd.MoreUpdate(operList);
        //            if (rsl.Result)
        //            {
        //                #region  向process中写入products的id  统计用
        //                var sql = "select distinct p.id ,p.plCode,p.rowNO from pi_ProductionPlan_products p " +
        //                    "inner join pi_ProductionPlan_process pr on pr.plCode = p.plCode and pr.rowNo = p.rowNO " +
        //                    "where p.isdel = 0 and pr.ppId is null";
        //                var ptable = cmd.GetDataTable(sql);
        //                operList = new List<OperateModel>();
        //                foreach (DataRow dr in ptable.Rows)
        //                {
        //                    gx = new DbPlanGongXu();
        //                    gx.plCode = dr["plCode"].ToString();
        //                    gx.rowNo = dr["rowNo"].ToString();
        //                    gx.ppId = dr["id"].ToString();
        //                    oper = new OperateModel();
        //                    oper.Types = OperateModel.OperateType.Edit;
        //                    oper.Conditions = "plCode,rowNo";
        //                    oper.Data = gx;
        //                    operList.Add(oper);
        //                }
        //                rsl = cmd.MoreUpdate(operList);

        //                #endregion
        //            }
        //            else
        //            {
        //                return rsl;
        //            }
        //        }//else end
        //    }
        //    catch (Exception ex)
        //    {
        //        rsl.Message = "第" + (temI + 1) + "行" + ex.Message;
        //        return rsl;
        //    }
        //    return rsl;
        //    #endregion

        //}//function end
        /// <summary>
        /// 生产计划审批
        /// </summary>
        /// <param name="plCodes">计划号</param>
        /// <param name="appCode">审核编码</param>
        /// <param name="userCode">审核人员</param>
        /// <returns></returns>
        public ReturnResult ApprovingPlan(string plCodes, string appCode, string userCode = "")
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                oper = new OperateModel();
                DbProductionPlan plan;
                var arr = plCodes.Split(',');
                foreach (string plCode in arr)
                {
                    if (!string.IsNullOrWhiteSpace(plCode))
                    {

                        plan = new DbProductionPlan();
                        plan.plCode = plCode;
                        plan.pStatus = appCode;
                        oper.Data = plan;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "plCode";
                        operList.Add(oper);
                    }
                }
                if (!string.IsNullOrWhiteSpace(plCodes))
                {
                    DbApproveRecord r = new DbApproveRecord();
                    r.createtime = getNow();
                    r.memo = "生产计划审批";
                    r.result = appCode;
                    r.businessCode = plCodes;
                    r.businessType = "P-Approve";
                    if (string.IsNullOrWhiteSpace(userCode))
                    {
                        r.createuser = userLogin.UserInfo().userCode;
                    }
                    else
                    {
                        r.createuser = userCode;
                    }
                    oper = new OperateModel();
                    oper.Data = r;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 添加备料信息
        /// </summary>
        /// <param name="keyCode"></param>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddTempBeiLiao(string keyCode, string datas)
        {
            rsl = new ReturnResult();
            try
            {
                string key = userLogin.UserInfo().userCode + keyCode;
                var data = Tools.Cache.GetCache(key);
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                if (data != null)
                {
                    list = (List<Dictionary<string, string>>)data;
                }
                var objs = JsonConvert.DeserializeObject<List<JObject>>(datas.ToString());
                #region
                foreach (var obj in objs)
                {
                    bool isAdd = true;
                    string proCode = obj["proCode"].ToString();
                    string color = obj["color"].ToString();
                    string wareCode = obj["wareCode"].ToString();
                    string positionCode = obj["positionCode"].ToString();
                    string shangbiao = obj["shangbiao"].ToString();
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (proCode == list[i]["proCode"].ToString() && positionCode == list[i]["positionCode"].ToString()
                            && color == list[i]["color"].ToString() && wareCode == list[i]["wareCode"].ToString() && shangbiao == list[i]["shangbiao"].ToString())
                        {
                            var sum = (double.Parse(list[i]["number"].ToString()) + double.Parse(obj["usedNum"].ToString())).ToString();
                            if (double.Parse(sum) > double.Parse(obj["number"].ToString()))
                            {
                                rsl.Message = "确认后使用数量（" + sum + "）将超过库存数量（" + obj["number"].ToString() + ")";
                                return rsl;
                            }
                            list[i]["number"] = (double.Parse(list[i]["number"].ToString()) + double.Parse(obj["usedNum"].ToString())).ToString();
                            isAdd = false;
                            break;
                        }
                    }
                    #region 添加方法
                    if (isAdd)
                    {
                        var d = new Dictionary<string, string>();
                        d["proCode"] = proCode;
                        d["proName"] = obj["proName"].ToString();
                        d["color"] = color;
                        d["wareCode"] = wareCode;
                        d["wareName"] = obj["wareName"].ToString();
                        d["positionCode"] = positionCode;
                        d["cPosName"] = obj["cPosName"].ToString();
                        d["shangbiao"] = shangbiao;
                        d["total"] = obj["number"].ToString();
                        d["number"] = obj["usedNum"].ToString();
                        d["key"] = Guid.NewGuid().ToString().Replace("-", "");
                        list.Add(d);
                    }
                    #endregion
                }
                #endregion
                Tools.Cache.SetCache(key, list);
                rsl.Message = "选择成功";
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 添加退料信息
        /// </summary>
        /// <param name="keyCode"></param>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddTempTuiLiao(string keyCode, string datas,string condition=null)
        {
            rsl = new ReturnResult();
            try
            {
                string key = userLogin.UserInfo().userCode + keyCode;
                var data = Tools.Cache.GetCache(key);
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                if (data != null)
                {
                    list = (List<Dictionary<string, string>>)data;
                    //list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(data.ToString());
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (var s in list)
                    {
                        if (json["rows"].ToString().Contains(s["id"].ToString()))
                        {
                            if (string.IsNullOrWhiteSpace(json["positionCode"].ToString()))
                            {
                                s["houseCode"] = json["houseCode"].ToString();
                                s["houseName"] = json["houseName"].ToString();
                            }
                            else if (string.IsNullOrWhiteSpace(json["houseCode"].ToString())) 
                            {
                                s["positionCode"] = json["positionCode"].ToString();
                                s["positionName"] = json["positionName"].ToString();
                            }

                        }
                    }
                }
                else
                {
                    //var objs = JsonConvert.DeserializeObject<List<JObject>>(datas.ToString());
                    var objs = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(datas);
                   
                    foreach (var obj in objs)
                    {
                        #region 添加方法

                        var d = new Dictionary<string, string>();
                        d["id"] = obj["id"].ToString();
                        d["prlCode"] = obj["prlCode"].ToString();
                        d["proCode"] = obj["proCode"].ToString();
                        d["proName"] = obj["proName"].ToString();
                        d["cu_yanse"] = obj["cu_yanse"].ToString();
                        d["cu_shangbiao"] = obj["cu_shangbiao"].ToString();
                        d["spec"] = obj["spec"].ToString();
                        d["houseCode"] = obj["houseCode"].ToString();
                        d["houseName"] = obj["houseName"].ToString();
                        d["positionCode"] = obj["positionCode"].ToString();
                        d["positionName"] = obj["positionName"].ToString();

                        d["nNum"] = obj["nNum"].ToString();
                        d["bakNum"] = obj["bakNum"].ToString();
                        d["key"] = Guid.NewGuid().ToString().Replace("-", "");
                        list.Add(d);

                        #endregion
                    }
                   
                }

                Tools.Cache.SetCache(key, list);
                rsl.Data = list;
                rsl.Message = "";
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 加载临时备料信息
        /// </summary>
        /// <param name="keyCode"></param>
        /// <returns></returns>
        public ReturnResult loadTempBeiLiao(string keyCode)
        {
            rsl = new ReturnResult();
            try
            {
                string key = userLogin.UserInfo().userCode + keyCode;
                var data = Tools.Cache.GetCache(key);
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                if (data != null)
                {
                    list = (List<Dictionary<string, string>>)data;
                }
                if (list.Count > 0)
                {
                    rsl.Data = list;
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "没数据";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 更改数量
        /// </summary>
        /// <param name="keyId">id</param>
        /// <param name="number">数量</param>
        /// <param name="keyCode">临时编码</param>
        /// <returns></returns>
        public ReturnResult ChanageTempBeiLiaoNum(string keyId, string number, string keyCode)
        {
            rsl = new ReturnResult();
            try
            {
                string key = userLogin.UserInfo().userCode + keyCode;
                var data = Tools.Cache.GetCache(key);
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                if (data != null)
                {
                    list = (List<Dictionary<string, string>>)data;
                }
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i]["key"] == keyId)
                    {
                        list[i]["number"] = number;
                        break;
                    }
                }
                Tools.Cache.SetCache(keyCode, list);
                rsl.Result = true;


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="keyCode"></param>
        /// <returns></returns>
        public ReturnResult DelTempBeiLiaoNum(string keyId, string keyCode)
        {
            rsl = new ReturnResult();
            try
            {
                string key = userLogin.UserInfo().userCode + keyCode;
                var data = Tools.Cache.GetCache(key);
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                if (data != null)
                {
                    list = (List<Dictionary<string, string>>)data;
                }
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i]["key"] == keyId)
                    {
                        list.Remove(list[i]);
                        break;
                    }
                }
                Tools.Cache.SetCache(keyCode, list);
                rsl.Result = true;


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        //tzzh 是否是组合套装 
        //proCode 主件编码（取的计划中存货编码）
        public ReturnResult SaveTempBeiLiao(string keyCode, string proId, string userCodes, string userNames, string memo, string tzzh, string proCode)
        {
            rsl = new ReturnResult();
            try
            {
                string key = userLogin.UserInfo().userCode + keyCode;
                var data = Tools.Cache.GetCache(key);
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                List<Dictionary<string, string>> newList = new List<Dictionary<string, string>>();
                if (data != null)
                {
                    list = (List<Dictionary<string, string>>)data;
                }
                if (list.Count < 1)
                {
                    rsl.Message = "没有要保存的数据";
                    return rsl;
                }

                string sql = "select * from pi_ProductionPlan_products where id in(" + proId + ")";
                var table = cmd.GetDataTable(sql);

                //newList = list.GroupBy(x => x.wareCode).Select(x => new BModel { ID = x.Key, TS = x.ToList() });
                #region 获取出库仓库（去重后的）
                List<string> warelist = new List<string>();
                foreach (var d in list)
                {
                    if (!warelist.Contains(d["wareCode"].ToString()))
                        warelist.Add(d["wareCode"].ToString());
                }
                #endregion

                #region 将list转为datatable
                DataTable dt = new DataTable();
                int i = 0;
                foreach (var s in list)
                {
                    #region 第一次循环，需要填上列名
                    if (i == 0)
                    {
                        foreach (var colName in s.Keys)
                        {
                            dt.Columns.Add(colName, typeof(string));
                        }
                        i++;
                    }
                    #endregion
                    DataRow dr = dt.NewRow();
                    foreach (KeyValuePair<string, string> item in s)
                    {
                        dr[item.Key] = item.Value;
                    }
                    dt.Rows.Add(dr);

                }
                #endregion

                #region 套装的其他入 和 子件的其他出
                if (tzzh == "1")
                {//备料如果是套装组合，需要做形态转换
                    #region 子件生成其他出库

                    U8_13 u8 = new U8_13();
                    rsl = u8.OtherOut(dt, warelist, "299");
                    if (!rsl.Result)
                        return rsl;
                    #endregion

                    #region 主件生成其他入库
                    var ware = "";//入库仓库
                    sql = "select parCode, parValue from sys_parameters_info " +
                        "where parCode = 'tzrkck' and isdel = 0 and enable = 'open' ";
                    var wareTable = cmd.GetDataTable(sql);
                    if (wareTable.Rows.Count > 0)
                    {
                        ware = wareTable.Rows[0]["parValue"].ToString();
                    }
                    else
                    {
                        ware = "012";//图强备货库
                    }
                    rsl = u8.OtherIn(table, ware, "199");
                    if (!rsl.Result)
                        return rsl;
                    #endregion

                }
                #endregion

                #region 创建备料单
                string plCodes = "", rowNo = "";
                foreach (DataRow r in table.Rows)
                {
                    plCodes += r["plCode"].ToString() + ",";
                    rowNo += r["rowNO"].ToString() + ",";
                }
                PlanPaiChanBLL paiChanBLL = new PlanPaiChanBLL();
                rsl = paiChanBLL.AddMaterialOutRecords(plCodes.TrimEnd(','), rowNo.TrimEnd(','), proId, list, userCodes, userNames, memo, tzzh);
                #endregion

                Tools.Cache.RemoveAllCache(key);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult SaveChangeTagPlan(string taskCode,string datas)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var json = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(datas);

                //责任人必填 因为改标申请只有一行，所以这只取了[0]
                if (string.IsNullOrWhiteSpace(json[0]["relationPeople"].ToString()))
                {
                    rsl.Message = "请选择责任人";
                    return rsl;
                }

                var sql_template = "select * from sys_TaskCenter_info where taskCode = '{0}'";
                var sql = string.Format(sql_template, taskCode);

                var table = cmd.GetDataTable(sql);
                var products = JsonConvert
                    .DeserializeObject<List<Restock_Keyword>>(table.Rows[0]["contents"].ToString());

                #region 计划编码不存在，生成新的计划编码
                string codeLength = Tools.ConfigReader.Reader["CodeLength"];
                string pCode = "CT";

                var plCode = CreatePlanCodeInfo(pCode, "生产计划编码", int.Parse(codeLength));
                #endregion

                // 主表
                var main = new DbProductionPlan
                {
                    plCode = plCode,
                    plType = "P-ChangeTag",
                    number = products
                            .Sum(p => decimal.Parse(p.number)).ToString(),
                    status = "ps-pg-set",
                    createtime = getNow(),
                    createuser = userLogin.UserInfo().userCode,
                    isdel = 0,
                    pLevel = "100",
                    pStatus = "pass"
                };
                oper = new OperateModel
                {
                    Types = OperateModel.OperateType.Add,
                    Data = main
                };
                operList.Add(oper);

                // 子表
                var number = 1;
                var prlCode = "";
                var relationOrder = "";
                foreach (var p in products)
                {
                    prlCode = plCode + "-" + number;
                    relationOrder += plCode + "-" + number+",";
                    var child = new DbProductionPlanPro
                    {
                        orderCode = "",
                        prlCode = prlCode,
                        plCode = plCode,
                        proCode = p.proCode,
                        number = p.number,
                        status = "ps-pg-set",
                        rowNO = number.ToString(),
                        isdel = 0,
                        createtime = getNow(),
                        createuser = userLogin.UserInfo().userCode,
                        cu_shangbiao = p.shangbiao,
                        cu_yanse = p.color,
                    };
                    oper = new OperateModel
                    {
                        Data = child,
                        Types = OperateModel.OperateType.Add
                    };
                    operList.Add(oper);
                    number++;
                }

                // 更改状态
                var taskCenter = new DbTaskCenter
                {
                    taskCode = taskCode,
                    relationPeople = json[0]["relationPeople"].ToString(),
                    relationOrder= relationOrder.TrimEnd(','),
                    isFinish = 1
                };
                oper = new OperateModel
                {
                    Data = taskCenter,
                    Conditions = "taskCode",
                    Types = OperateModel.OperateType.Edit
                };
                operList.Add(oper);

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult CreateChangeTag_FromSaleOrder(string jsonStr)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();

            try
            {

                //var jObj = JsonConvert.DeserializeObject<JObject>(jsonStr);
                var jObj = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonStr);
                var a = jObj;
                //var jArr = jObj["data"][0]["spec"].ToString();
                foreach (var s in jObj)
                {
                    var jArr = s;

                    var sql = "select * from sys_parameters_info where parCode = 'rs_ct_config'";
                    var dt = cmd.GetDataTable(sql);

                    var configString = dt.Rows[0]["parValue"].ToString();
                    var rc_config = JsonConvert.DeserializeObject<Rs_Ct_Config>(configString);

                    // 需要检查现存量的仓库
                    var houseString = "'";
                    foreach (var house in rc_config.restock.outWarehouse)
                    {
                        houseString += house;
                        houseString += "',";
                    }
                    houseString = houseString.TrimEnd(',');

                    // 改标计划申请单
                    var taskCode = getTimeString();
                    var changeTagList = new List<Restock_Keyword>();

                    changeTagList.Add(new Restock_Keyword
                    {
                        proCode = jArr["proCode"].ToString(),
                        proName = jArr["proName"].ToString(),
                        spec = jArr["spec"].ToString(),
                        color = jArr["cu_yanse"].ToString(),
                        shangbiao = jArr["cu_shangbiao"].ToString(),
                        number = jArr["number"].ToString(),
                    });

                    //foreach (var j in jArr)
                    //{
                    //    changeTagList.Add(new Restock_Keyword
                    //    {
                    //        proCode = j["proCode"].ToString(),
                    //        proName = j["proName"].ToString(),
                    //        spec = j["spec"].ToString(),
                    //        color = j["cu_yanse"].ToString(),
                    //        shangbiao = j["cu_shangbiao"].ToString(),
                    //        number = j["number"].ToString(),
                    //    });
                    //}

                    var changeTagJson = JsonConvert.SerializeObject(changeTagList);
                    var toUsers = "";
                    foreach (var u in rc_config.restock.toUser)
                    {
                        toUsers += u + ',';
                    }
                    var changeTagTask = new DbTaskCenter
                    {
                        id = taskCode,
                        businessType = "changeTag",
                        businessId = DateTime.Now.ToString("yyyy-MM-dd"),
                        //toUser = rc_config.changeTag.toUser,
                        toUser = toUsers.TrimEnd(','),
                        contents = changeTagJson,
                        createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        createuser = userLogin.UserInfo().userCode,
                        isFinish = 0,
                        taskCode = taskCode,
                        memo = "销售订单生成改标申请单",
                    };

                    oper = new OperateModel
                    {
                        Types = OperateModel.OperateType.Add,
                        Data = changeTagTask
                    };
                    operList.Add(oper);
                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除改标申请单
        /// </summary>
        /// <param name="id">申请单id</param>
        /// <returns></returns>
        public ReturnResult DelTask(string id)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                #region 删除方法
                DbTaskCenter task = new DbTaskCenter();
                task.id = id;
                oper = new OperateModel();
                oper.Data = task;
                oper.Types = OperateModel.OperateType.Delete;
                oper.Conditions = "id";
                operList.Add(oper);
                #endregion

                rsl = cmd.MoreUpdate(operList);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


    }
}
